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.
vijay on December 7th, 2007 at 3:11 PM says:
er
aren’t both code chunks the same?!!
even my diff, says they’re the same, so they’ve gotta be the same
admin on December 18th, 2007 at 9:06 AM says:
Hey Vijay, you’re right, just fixed it.
Stephen O'Reilly on January 29th, 2008 at 7:32 AM says:
What’s the status of CSpace?