Hey Experts!
I want to know the prototype chaining? How does it take part in Inheritance in JavaScript?
I want to know the prototype chaining? How does it take part in Inheritance in JavaScript?
function Super(){ this.a = 100; } function Sub(){ Super.apply(this,arguments); } function test(){ Sub.prototype = new Super(); Super.prototype.x = 200; Sub s = new Sub(); alert(s.a); alert(s.x); }
function Sub(){ this.b = 200; ..... }
function Mammal(name){ this.name=name; this.offspring=[]; } Mammal.prototype.haveABaby=function(){ var newBaby=new [B]this.constructor[/B]("Baby "+this.name); this.offspring.push(newBaby); return newBaby; } Mammal.prototype.toString=function(){ return '[Mammal "'+this.name+'"]'; } Cat.prototype = new Mammal(); // Here's where the inheritance occurs /* comment out this line and compare the output to the original one */ [U]Cat.prototype.constructor=Cat;[/U] // Otherwise instances of Cat would have a constructor of Mammal function Cat(name){ this.name=name; } Cat.prototype.toString=function(){ return '[Cat "'+this.name+'"]'; } var myPet = new Cat('Felix'); myPet.haveABaby(); // calls a method inherited from Mammal alert(myPet.offspring[0]); // results in '[Cat "Baby Felix"]'
Comment