Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub.prototype = new Base() vs Sub.prototype = Base.prototype [duplicate]

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?

like image 807
Maciej Sz Avatar asked Oct 27 '25 15:10

Maciej Sz


2 Answers

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.

like image 64
Chris Jester-Young Avatar answered Oct 29 '25 05:10

Chris Jester-Young


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

like image 30
Mulan Avatar answered Oct 29 '25 04:10

Mulan