1

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.

David G
  • 94,763
  • 41
  • 167
  • 253
kotio
  • 13
  • 2
  • Exact same problem as in [Why can't I call a prototyped method in Javascript?](http://stackoverflow.com/questions/12500637/why-cant-i-call-a-prototyped-method-in-javascript) – Bergi Apr 20 '13 at 20:14

1 Answers1

1

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; 
gnerkus
  • 11,357
  • 6
  • 47
  • 71
  • [Don't use `new` for creating prototype instances objects!](http://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here) – Bergi Apr 20 '13 at 20:04