This is a really old subject about which much has been written, but I haven't found exactly this spin on it so please bear with me.
After having spent a bit of time trying to get my head around the new
and f.prototype
constructor constructs in JavaScript, and reading about how it's a prototypal language, not to mention Crockford's illuminating comments on the subject, I have reached the conclusion that the following is a much more natural way to simulate traditional class-based inheritance in JavaScript, should one want to:
// emphasise that there's no superclass instead of writing A = {}
var A = Create.object(null);
// define the 'instance initializer', which half of what a constructor is
A.init = function(x, y) {
this.x = x;
this.y = y;
return this;
}
// a method
A.sum = function() {
return this.x + this.y;
}
// instantiate A
var a = Object.create(A).init(3);
// a subclass
var B = Object.create(A);
B.init = function(x, y, w) {
A.init.call(this, x, y);
this.w = w;
return this;
}
B.weightedSum = function() {
return (1.0 - this.w) * this.x + this.w * this.y;
}
// instantiate B
var b = Object.create(B).init(1, 2, 0.3);
// equivalent of `instanceof`
var bInstanceOfA = A.isPrototypeOf(b);
What I like about this is that it exposes what's really going as there is clear separation between object creation (which applies to both instantiation and subclassing) and initialization (which only applies to instantiation). Also there is symmetry between creating a base class and a subclass. The code doesn't require externally defined functions or libraries, but isn't particularly verbose either.
My question, therefore, is the following: could those of you who have more experience with JavaScript tell me if there are problems with the approach that I am not considering, or if it is a good pattern?