Skip to content

Instantly share code, notes, and snippets.

@jesusalber1
Last active December 2, 2015 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesusalber1/65514b048fc01af539b0 to your computer and use it in GitHub Desktop.
Save jesusalber1/65514b048fc01af539b0 to your computer and use it in GitHub Desktop.
Why !(this instanceof Object)?
/* http://stackoverflow.com/questions/22211755/function-f-if-this-instanceof-f-return-new-f,
If constructor is called without 'new' keyword before, it returns a new instance of the object. */
function MyObject(foo){
if (!(this instanceof MyObject)){
return new MyObject(foo);
}
this.bar = foo;
}
/* Testing... */
var newObject1 = new MyObject('First option');
var newObject2 = MyObject('Second option');
/* So newObject1 and newObject2 are instances of MyObject */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment