O GoConqr está de visual novo! Conte para nós o que você achou.

Notas

Inheritence in Javascript

bikram patnaik Learning Technology Inglês 1 página

Conteúdo das notas (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”.

Informações

Descrição
Learning Technology Notas sobre Inheritence in Javascript, criado por bikram patnaik em 25-04-2017.
Criado por
bikram patnaik · abr 2017
Atualizado
27 abr 2017
Visualizações
0
Avaliação

Fale Conosco

Sobre o que é sua mensagem?

O que você acha do novo visual?

Você gostou?