GoConqr has a new look! Let us know what you think.

Notes

Inheritence in Javascript

bikram patnaik Learning Technology English 1 page

Content of the notes (1)

Page 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”.

Information

Description
Learning Technology Note on Inheritence in Javascript, created by bikram patnaik on 25/04/2017.
Created by
bikram patnaik · Apr 2017
Updated
Apr 27, 2017
Views
0
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?