JavaScript inheritance issue

Could you explain the difference between the two codes below?

function Person(){} Person.prototype.dance = function(){}; function Ninja(){} Ninja.prototype = Person.prototype; 

and

 function Person(){} Person.prototype.dance = function(){}; function Ninja(){} Ninja.prototype = new Person(); 

I am a little confused on these lines:

 Ninja.prototype = Person.prototype; 

and

 Ninja.prototype = new Person(); 

I found out that the second supports Inheritance, and the first does not. Can you explain to me what magic is in the second?

+7
source share
1 answer
  • Setting Ninja.prototype = Person.prototype; says that all ninjas are people, and all people are ninjas, as they simply force two prototypes to point to the same thing. Therefore, changing Ninja.prototype will change to Person.prototype and vice versa.

  • Setting Ninja.prototype = new Person(); means that all ninjas begin to be an ordinary person, but Ninja.prototype can be changed without changing the definition of Person . The key point here is the new keyword, which creates a unique instance of Person and therefore can be changed without any changes.


Example Ninja.prototype = Person.prototype

Define a Ninja prototype to be the same as Person's:

 function Person() {} Person.prototype.dance = function () {}; // A Person can dance function Ninja() Ninja.prototype = Person.prototype; // Now a Ninja can dance too! 

The Ninja instance has Person features:

 var ninja = new Ninja(); ninja.dance(); 

But , changes to the Ninja definition also affect Person instances:

 Ninja.prototype.kill = function () {}; // Oh no! Now a Person can kill too! var bob = new Person(); bob.kill(); // Not what we wanted... 

Example Ninja.prototype = new Person()

Define Person as before:

 function Person(){}; Person.prototype.dance = function () {}; // A Person can dance 

Now I will break Ninja.prototype = new Person() in two steps. First create a new Person called defaultNinja :

 var defaultNinja = new Person(); // Despite the name, it just a regular Person 

Then define all Ninja as default:

 function Ninja(){}; Ninja.prototype = defaultNinja; // Really the same as Ninja.prototype = new Person(); 

This time, if we change what Ninja can do:

 Ninja.prototype.kill = function () {}; // OR, defaultNinja.kill = function () {}; 

Person instances are not affected:

 ninja.kill(); // Now the ninja can kill var bob = new Person(); bob.kill(); // ERROR, because Person.prototype doesn't have kill(), // only defaultNinja does 
+14
source

All Articles