Can you please explain the difference between two codes mentioned 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 little confused at these lines:
Ninja.prototype = Person.prototype;
and
Ninja.prototype = new Person();
I came to know the second one supports Inheritance and the first one not, Can you explain me what is the magic in the second one?
Setting
Ninja.prototype = Person.prototype;is saying that all Ninjas are Persons, and all Persons are Ninjas, since it simply makes the two prototypes point to the same thing. So changingNinja.prototypewill changePerson.prototypeand vice versa.Setting
Ninja.prototype = new Person();is saying that all Ninjas start off being a regular person, butNinja.prototypecan be modified without changing the definition ofPerson. The key here is thenewkeyword, which creates a unique instance ofPerson, and is therefore free to be modified without affecting anything else.Example of
Ninja.prototype = Person.prototypeDefine
Ninja‘s prototype to be the same as Person’s:An instance of
Ninjahas the abilities ofPerson:But, modifications to the definition of
Ninjaalso affect instances ofPerson:Example of
Ninja.prototype = new Person()Define
Personin the same way as before:Now I’ll break
Ninja.prototype = new Person()into two steps. First, create a newPerson, calleddefaultNinja:Then define all
Ninjas to be like the default:This time if we change what
Ninjas can do:Instances of
Personaren’t affected: