javascript inheritance with prototype - redundant object -


i'm reading tutorial inheritance in javascript, , there following statement:

for object of rabbit class inherit animal class need:

  1. define animal
  2. define rabbit
  3. inherit rabbit animal:

    rabbit.prototype = new animal()

they approach has disadvantage of need create redundant object. don't understand why need create redundant object? i've tried following , worked without creating redundant objects:

function animal() {}; function rabbit() {}; rabbit.prototype = animal.prototype animal.prototype.go = function() {alert("i'm inherited method"}; var r = new rabbit(); r.go(); 

what missing here?

what you're missing code, rabbit , animal share exact same prototype. if added eatcarrot method rabbit every other animal have method too.

the tutorial you're using out of date. preferred way subclass instead use object.create create brand new prototype object rabbit chains animal.prototype:

rabbit.prototype = object.create(animal.prototype); rabbit.prototype.constructor = rabbit; 

note not depend on subclassing rabbit instance of animal.

see mdn more information.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -