¡GoConqr estrena diseño! Cuéntanos qué te parece.

Apuntes

Inheritence in Javascript

bikram patnaik Learning Technology Inglés 1 página

Contenido del apunte (1)

Página 1

Inheritance in Javascript

There are only 3 methods of interest for setting up inheritance in JavaScript:

Pseudoclassical Inheritance:1demiurge.extend( TargetClass, SourceClass )

Object augmentation:1demiurge.decorate( target, SourceClass )

Prototypal inheritance:1demiurge.createObject( object )

Pseudo classical Pattern The Pseudoclassical pattern tries to replicate inheritance in a way that is familiar to those who come from a Java or C like background. By using Pseudoclassical inheritance, we attempt to recreate classic programming language’s behavior by using class wide inheritance and where objects are instances of those classes.

A pattern which uses a constructor function and the new operator, combined with a prototype added to the constructor is said to be Pseudoclassical.

In JavaScript, one way to do this inheritance is:

Invoke a constructor function.

Point a child’s prototype to the parent’s prototype for inheritance to occur.

/**

* Point a child's prototype to a parent's prototype

**/

var extendObj = function(childObj, parentObj) {

childObj.prototype = parentObj.prototype;

};

// base human object

var Human = function() {};

// inhertiable attributes / methods

Human.prototype = {

name: '',

gender: '',

planetOfBirth: 'Earth',

sayGender: function () {

alert(this.name + ' says my gender is ' + this.gender);

},

sayPlanet: function () {

alert(this.name + ' was born on ' + this.planetOfBirth);

}

};

// male ---------//

var Male = function (name) {

this.gender = 'Male';

this.name = 'David';

};

extendObj(Male, Human);// inherits human

// female ---------//

var Female = function (name) {

this.name = name;

this.gender = 'Female';

};

extendObj(Female, Human); // inherits human

// new instances

var david = new Male('David');

var jane = new Female('Jane');

david.sayGender(); // David says my gender is Male

jane.sayGender(); // Jane says my gender is Female .

Male.prototype.planetOfBirth = 'Mars';

david.sayPlanet(); // David was born on Mars

jane.sayPlanet(); // Jane was born on Mars

As expected, we have achieved inheritance in a Pseudoclassical manner, however, this solution has a problem.

If you look at the last line, you will see the alert says Jane was born on Mars, but what we really want it to say is Jane was born on Earth.

The reason for this is the Male prototype was changed to “Mars”.

Información

Descripción
Learning Technology Apunte sobre Inheritence in Javascript, creado por bikram patnaik el 25/04/2017.
Creado por
bikram patnaik · abr 2017
Actualizado
27 abr 2017
Visitas
0
Valoración

Escríbenos

¿Sobre qué es tu mensaje?

¿Qué te parece el nuevo diseño?

¿Te gusta?