Skip to content

Instantly share code, notes, and snippets.

@pixyj
Created November 28, 2013 06:48
Show Gist options
  • Save pixyj/7688171 to your computer and use it in GitHub Desktop.
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
//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