4 ms·
Whenever I find myself needing to roll my own class-based system in JavaScript I use this function: function subclass(constructor, superConstructor) {
by curtis 14y ago
Whenever I find myself needing to roll my own class-based system in JavaScript I use this function:
function subclass(constructor, superConstructor)
{
function surrogateConstructor()
{
}
surrogateConstructor.prototype = superConstructor.prototype;
var prototypeObject = new surrogateConstructor();
prototypeObject.constructor = constructor;
constructor.prototype = prototypeObject;
}
Then you can say things like:
subclass(DerivedConstructor, BaseConstructor);
There's a full write-up of this approach at http://www.golimojo.com/etc/js-subclass.html http://www.golimojo.com/etc/js-subclass.html.
- epidemian 14y agoThis technique of the surrogate constructor is exactly what CoffeeScript uses under the table when using the extends operator. E.g. http://coffeescript.org/#try:class%20Derived%20extends%20Base http://coffeescript.org/#try:class%20Derived%20extends%20Bas.... It also copies all the properties on the super constructor to the derived constructor, so you can have the "class level methods" in the derived classes too. One of the main benefits i found of using CoffeeScript's sugar for classical inheritance is that i no longer need to stop and think "ok, so am i doing things right here?" every time i inherit from a class or call a "super" method, which was the case when writing JS. It Just Works (TM).