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:
- define animal
- define rabbit
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
Post a Comment