Skip to content

Instantly share code, notes, and snippets.

@chriscummings
Created May 30, 2011 05:15
Show Gist options
  • Save chriscummings/998482 to your computer and use it in GitHub Desktop.
Save chriscummings/998482 to your computer and use it in GitHub Desktop.
Dealing with new not being used when calling constructors in JS
// Quietly just handle the issue - but requires remembering to write the constructor name in the check!
// =====================================================================================================
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...
}
// Throw an excpetion
// =====================================================================================================
function Foo(){
if ( !(this instanceof arguments.callee) ){
throw new Error("Constructor called as a function");
}
// constructor logic follows...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment