One of javascript pitfalls is object constructor: if you forgot to add new
before your function, it will not be called as constructor, but as usual function.
Last active
August 29, 2015 13:57
-
-
Save timmarinin/9604322 to your computer and use it in GitHub Desktop.
Foolproof constructor for objects
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
var Human = function Human() { | |
this.age = 5; | |
this.askAge = function() { | |
return "My age is " + age; | |
} | |
} | |
//Problem lies here: forgot to add `new` | |
var Mike = Human(); | |
//and Mike is undefined | |
console.log(Mike); // undefined | |
//but now window has age and askAge() properties | |
console.log(window.age); // 5 |
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
var Human = function Human() { | |
//and there it is. | |
if (this === window) return new Human(arguments); | |
this.age = 5; | |
this.askAge = function() { | |
return "My age is " + age; | |
} | |
} | |
//And our problem goes away | |
var Mike = Human(); | |
//and now window has age and askAge() properties | |
console.log(age); // ReferenceError: age is not defined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment