Oct 04

One of the cool things about javascript is prototypal inheritance. The not so cool thing is that I often forget to put a new before a constructor call. A constructor call is nothing but a function call with a ‘new’ prefix. Forget the new prefix and the `this` passed to the function is the global window object.

function Foo( a, b ) {
    this.prop_a = a;
    this.prop_b = b;
}

var f = Foo( 1, 2 ) // Wrong way
// Now the global window object has prop_a & prob_b properties and f is undefined
var f1 = new Foo(1,2)   // The right way

I found a nice solution to this problem quite some time ago in the MochiKit source, and I’ve been using this ever since.

function Foo( a, b ) {
    var cls = arguments.callee;
    if(!(this instanceof cls)) {
        return new cls(a,b);
    }
    this.prop_a = a;
    this.prop_b = b;
}
var f = Foo( 1, 2 );    // Works anyways

Here, the constructor checks if this is an instance of itself (arguments.callee) if not, it returns a new instance of itself.