Created
November 28, 2013 06:48
-
-
Save pixyj/7688171 to your computer and use it in GitHub Desktop.
Why you shouldn't miss new when invoking a constructor function in javascript
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
//taken from Object Oriented Javascript by Stoyan Stefanov | |
var Hero() { | |
this.occupation = "Ninja!" | |
this.say = function() { | |
return "I'm a " + this.occupation; | |
} | |
} | |
/* correct invocation of constructor function | |
> var h = new Hero() | |
> h.say() | |
> "I'm a Ninja!" | |
> this.say() | |
> undefined | |
*/ | |
/* wrong invocation. The global object is 'clobbered' | |
> var h2 = Hero() | |
> undefined | |
> this.say() | |
> "I'm a Ninja!" | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment