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?
setting
ninja.prototype = person.prototype;saying all ninjas persons, , persons ninjas, since makes 2 prototypes point same thing. changingninja.prototypechangeperson.prototype, vice versa.setting
ninja.prototype = new person();saying all ninjas start off being regular person,ninja.prototypecan modified without changing definition ofperson. key herenewkeyword, creates unique instance ofperson, , 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
Post a Comment