Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created November 2, 2012 13:12
Show Gist options
  • Save bloodyowl/4001307 to your computer and use it in GitHub Desktop.
Save bloodyowl/4001307 to your computer and use it in GitHub Desktop.
JS Tip : safe constructor

JS Tip : safe constructor

To prevent context issues (understand this is not what you expected), you can make the new keyword optional with constructors.

In fact, if this isn't a object that was just created by the function, a recursion that corrects the way the function is called is made.

function myConstructor (params) {
if (!(this instanceof myConstructor)) return new myConstructor(params);
// some code ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment