And yes, new
has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:
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...
}
Now you can have the advantages of new
without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as [some][2] commented, use the check to introduce a runtime exception:
if ( !(this instanceof arguments.callee) )
throw new Error("Constructor called as a function");
(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)
(Note using arguments.callee to check if you've been called with new may not be so good, since arguments.callee is not available in strict mode. Better to use the function name.)
http://ejohn.org/blog/simple-class-instantiation/
http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful
http://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful