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 () {};
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 () {};
Example Ninja.prototype = new Person()
Define Person as before:
function Person(){}; Person.prototype.dance = function () {};
Now I will break Ninja.prototype = new Person() in two steps. First create a new Person called defaultNinja :
var defaultNinja = new Person();
Then define all Ninja as default:
function Ninja(){}; Ninja.prototype = defaultNinja;
This time, if we change what Ninja can do:
Ninja.prototype.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
David tang
source share