mrdoob/three.js — Issue #1103: Remove the need for the 'new' keyword
Author: canassa
Created: 2012-01-13 22:15:13+00:00
State: open

I have a suggestion.

Currently, Three.js requires that each time a new object instance is created that you prefix the object constructor with the 'new' keyword. This can cause lots of trouble. If you forget to add the 'new', Javascript will pass silently and will cause some very hard to debug errors.

Some people avoid this by making a constructor function that returns the object. e.g.:

var foo = function () {
var pub= { };
return pub;
}
var bar = foo();

The problem with this approach is that it's very slow and will break the current API.

I was digging into this matter and I found this solution:
http://ejohn.org/blog/simple-class-instantiation/

In this blog post John suggests the following technic:

function foo()
{
// if user accidentally omits the new keyword, this will
// silently correct the problem...
if ( !(this instanceof foo) )
return new foo();

// constructor logic follows...
}

This will automatically correct the problem if someone forgets the 'new' keyword. John goes even further in his blog post and makes a wrapper function for this.