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:
- there is one less dummy instantiation of
Base
, which is obviously better as the instance is never used anyway - inspecting instances
shows that the first approach produces two nested
__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?