jquery - Question regarding Inheritance in JavaScript -


can please explain difference between 2 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 little confused @ these lines:

ninja.prototype = person.prototype;  

and

ninja.prototype = new person(); 

i came know second 1 supports inheritance , first 1 not, can explain me magic in second one?

  1. setting ninja.prototype = person.prototype; saying all ninjas persons, , persons ninjas, since makes 2 prototypes point same thing. changing ninja.prototype change person.prototype , vice versa.

  2. setting ninja.prototype = new person(); saying all ninjas start off being regular person, ninja.prototype can modified without changing definition of person. key here new keyword, creates unique instance of person, , therefore free modified without affecting else.


example of ninja.prototype = person.prototype

define ninja's prototype same person's:

function person() {} person.prototype.dance = function () {}; // person can dance  function ninja()  ninja.prototype = person.prototype; // ninja can dance too! 

an instance of ninja has abilities of person:

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

but, modifications definition of ninja affect instances of person:

ninja.prototype.kill = function () {}; // oh no! person can kill too! var bob = new person(); bob.kill(); // not wanted... 

example of ninja.prototype = new person()

define person in same way before:

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

now i'll break ninja.prototype = new person() 2 steps. first, create new person, called defaultninja:

var defaultninja = new person(); // despite name, it's regular person 

then define ninjas default:

function ninja(){}; ninja.prototype = defaultninja; // same ninja.prototype = new person(); 

this time if change ninjas can do:

ninja.prototype.kill = function () {}; // or, defaultninja.kill = function () {}; 

instances of person aren't affected:

ninja.kill(); // ninja can kill var bob = new person(); bob.kill(); // error, because person.prototype doesn't have kill(),             // defaultninja 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -