Monday, May 17, 2010

Inheritance and Polymorphism in Javascript

You must read before going further, I am going to use example from that

creating person class

function Person()
    this.eyes = 2;
    this.legs = 2;
    this.color = "white";

Inheriting Man class from Person

Man.prototype.constructor = Man; 
Man.prototype = new Person;

writing Man class now

function Man()
    this.color = "black";

Adding few properties in prototypes directly

Person.prototype.legs = 4;
Man.prototype.legs = 2; = "black";

creating objects
var p = new Person;
var m = new Man;

The prototype chain for m will look as following

On the same line you can create prototype chain for object p. Now to verify if your objects are actually inherited try following

alert(m instanceof Man);  //will pop up true
alert(m instanceof Person); // will pop up true


No comments:

Post a Comment