Last active
December 2, 2015 20:25
-
-
Save jesusalber1/65514b048fc01af539b0 to your computer and use it in GitHub Desktop.
Why !(this instanceof Object)?
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
/* 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