Skip to content

Instantly share code, notes, and snippets.

@nifl
Created November 26, 2012 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nifl/4150351 to your computer and use it in GitHub Desktop.
Save nifl/4150351 to your computer and use it in GitHub Desktop.
It is NOT 'bad' to use the new keyword. But if you forget it, you will be calling the object constructor as a regular function. If your constructor doesn't check its execution context then it won't notice that 'this' points to different object (ordinarily

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment