Javascript parent constructor being run when defining inheritance and a solution
Posted by Drakonen on January 23, 2012 in Uncategorized | Short Link
When using the traditional Javascript methods to do some sort of inheritance, the constructor of the parent will always be run when trying to inherit it. This seems to be a unfortunate side effect of using new a().
The problem
Consider this code. Here b inherits from a
function a() { console.log("a"); } function b() { a.call(this); console.log("b"); } b.prototype = new a(); // a's constructor will be run here! b.prototype.constructor = b; new b(); // run once new b(); // run twice
Here a’s constructor will be run 3 times.
a a b a b
The solution
There is a simple fix for this, but its only in Ecmascript 5.
Change this:
b.prototype = new a();
Into this:
b.prototype = Object.create(a.prototype);
And the constructor will only be run when actually being called:
a b a b