Given this bit of code:
var SuperClass = function(a, b) {
this.a = a;
this.b = b;
};
SuperClass.prototype.getA = function() {
return this.a;
};
var SubClass = function(a, b, c) {
SuperClass.call(this, a, b);
this.c = c;
};
In order to initiate the SubClass prototype, most recommendations seem to be the following:
SubClass.prototype = new SuperClass();
It seems odd to me to create (instantiate) a new SuperClass object (with its own a and b properties) just to serve as the prototype for the SubClass.
This also works:
// anti-pattern
SubClass.prototype = SuperClass.prototype;
but it passes the SuperClass.prototype object by reference, so anything you add to the SubClass.prototype is also added to the SuperClass.prototype, because they are the same object. This is not expected behavior in most cases.
QUESTION: Is there a way to achieve the proper prototyping without creating an instance of the SuperClass to serve as the SubClass‘s base prototype?
Under modern browsers:
This lets you create an object with a defined
__proto__without invoking the ‘constructor’ method of the parent class. For more details, read up onObject.create(including a polyfill implementation for older browsers).Seen in action: