Created
May 30, 2011 05:15
-
-
Save chriscummings/998482 to your computer and use it in GitHub Desktop.
Dealing with new not being used when calling constructors in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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