There are many resources online about JavaScript prototyping and inheritance. Most of which use code similar to this:
function Base() {}
function Sub() {}
with inheritance implemented like this:
Sub.prototype = new Base();
But I am wondering what is wrong with inheritance implemented this way instead:
Sub.prototype = Base.prototype;
It seems like the second is working just as well. The only two differences that I've spotted (which IMO are advantages of the second approach) are:
Base, which is obviously
better as the instance is never used anyway__proto__
properties whereas the second only single one, which makes the
instance cleaner.The latter is illustrated in below code snippet:
function Base(){}
Base.prototype.bogus = function(){};
function SubNew(){}
function SubProto(){}
SubNew.prototype = new Base();
SubProto.prototype = Base.prototype;
var sn = new SubNew();
var sp = new SubProto();
console.log(sn);
console.log(sp);
gives:

But I'm under the impression that I'm missing some very important point here. My question is: what is the case against the second approach?
When you add a new property to Sub.prototype, you wouldn't want it to affect Base.prototype, would you? That would be pretty broken. :-)
Using the new Base() approach means that any changes you make to Sub.prototype won't "leak through" to Base.prototype.
I would set it up like this
function Base() {}
function Sub() {
// call parent constructor; optional
Base.call(this);
}
Sub.prototype = Object.create(Base.prototype, {constructor: {value: Sub}});
This is very similar to how util.inherits works in node.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With