Inheritance


The basics of how prototypal inheritance works.
function Person(){}
Person.prototype.dance = function(){};
 
function Ninja(){}
 
// Achieve similar, but non-inheritable, results
Ninja.prototype = Person.prototype;
Ninja.prototype = { dance: Person.prototype.dance };

assert( (new Ninja()) instanceof Person, "Will fail with bad prototype chain." );
 
// Only this maintains the prototype chain
Ninja.prototype = new Person();
 
var ninja = new Ninja();
assert( ninja instanceof Ninja, "ninja receives functionality from the Ninja prototype" );
assert( ninja instanceof Person, "... and the Person prototype" );
assert( ninja instanceof Object, "... and the Object prototype" );
QUIZ: Let's try our hand at inheritance.
 function Person(){}
 Person.prototype.getName = function(){
   return this.name;
 };

 // Implement a function that inherits from Person
 // and sets a name in the constructor

 var me = new Me();
 assert( me.getName(), "A name was set." );

The result is rather straight-forward.
 function Person(){}
 Person.prototype.getName = function(){
   return this.name;
 };

 function Me(){
   this.name = "John Resig";
 }
 Me.prototype = new Person();

 var me = new Me();
 assert( me.getName(), "A name was set." );[/cod
  

你可能感兴趣的:(prototype)