Search code examples
javascriptinheritanceprototype-programming

Sub.prototype = new Base() vs Sub.prototype = Base.prototype


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:

code snippet output

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?


Solution

  • When you use the same prototype, you are not inheriting anything, you are just making another type that is a copy of the first.

    If you put anything in the base type object, it won't be inherited if you just get the prototype:

    function Base(){
      this.answer = 42;
    }
    
    function SubNew(){}
    function SubProto(){}
    
    SubNew.prototype = new Base();
    SubProto.prototype = Base.prototype;
    
    var sn = new SubNew();
    var sp = new SubProto();
    
    // show result in StackOverflow snippet
    document.writeln(sn.answer);
    document.writeln(sp.answer);