Skip to content

Instantly share code, notes, and snippets.

@timmarinin
Last active August 29, 2015 13:57
Show Gist options
  • Save timmarinin/9604322 to your computer and use it in GitHub Desktop.
Save timmarinin/9604322 to your computer and use it in GitHub Desktop.
Foolproof constructor for objects

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.

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
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