Reputation: 13
OK, let's say I have a constructor like this one:
var Base = function() {};
Base.prototype.shmoo = function() { this.foo="shmoo"; }
How to create other constructors extending Base
independently from it and separately from each other as well?
In other words extending functionality of a derived constructor affects only its objects and no other, neither Base
, neither another derived one.
I've tried
Extender = function() {};
Extender.prototype = Base.prototype;
Extender.prototype.moo = function() { this.moo="boo"; };
but that takes effect everywhere, of course.
Should I simulate class hierarchy? I try to stay away from that pattern.
Upvotes: 1
Views: 74
Reputation: 12019
This would implement prototypical inheritance (which is what you want):
// The Extender prototype is an instance of Base but not Base's prototype
Extender.prototype = new Base();
// Set Extender() as the actual constructor of an Extender instance
Extender.prototype.constructor = Extender;
Upvotes: 1