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
Facebook Twitter Email

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Copyright © 2005-2012 Draakwired All rights reserved.
The Shades theme, version 1.7, is a BuyNowShop.com creation.

Social links powered by Ecreative Internet Marketing