is this a good pattern for OO JS?
What I am looking for is an easy way to solve inheritance in JavaScript.
function MySuperClass(arg)
{
this.arg1 = arg;
}
function MyBaseClass(arg)
{
this.base = MySuperClass;
this.base(arg);
this.arg2 = arg;
}
MyBaseClass.prototype = new MySuperClass();
function MySpecificClass(arg)
{
this.base = MyBaseClass;
this.base(arg);
this.arg3 = arg;
}
//ensures inheritance of all properties
MySpecificClass.prototype = new MyBaseClass();
var myFirstInstance = new MySpecificClass("test");
var mySecondInstance = new MySpecificClass("test2");
Note: See the end for an ES2015 update.
ES5 and earlier
There are a couple of problems there.
Your
MySuperClassfunction expects an argument, but you can’t give it one when you’re calling it to create theMyBaseClass.prototype.The
baseproperty you’re setting on the instance won’t work correctly for the code inMyBaseClass, becauseMyBaseClassexpects that to beMySuperClass, but it isn’t, becauseMySpecificClasshas overwritten it.This is complex stuff. You’re very smart being sure to do three generations (
MySuperClass,MyBaseClass, andMySpecificClass), because it’s really easy to do this for just a two-level hierarchy, but for three+ levels, it’s much more complicated. 🙂If you want a thorough discussion of dealing with inheritance, calling into superclass methods, etc., in JavaScript, I’ve written an article on it, and written a toolkit for doing it. Reading the article and looking at the toolkit source (which goes beyond the article) may be useful in understanding how the prototype chain works and how to work with it.
Here’s an example not using any toolkit and not trying to make supercalls easy. To keep things clear, I’ve used the terms
Parent,Child, andGrandChildfor the three generations:Usage:
Testing instanceof, although if you’re using instanceof a lot, you might want to read up on duck typing:
If you’re not in an ES5-enabled environment, you can use this shim for
Object.create(note: not a complete shim, just enough to enable the above):You can see why a toolkit script makes life a bit easier. You have several to choose from. Here’s what the above looks like using
Lineage, my toolkit:Usage is the same.
ES2015 and later
As of ES2015 (aka “ES6”), JavaScript got the
classandsuperkeywords, which dramatically simplify the above, and can be used today with transpiling.