Skip to content

Instantly share code, notes, and snippets.

@CatTail
Created July 16, 2013 15:42
Show Gist options
  • Save CatTail/6009885 to your computer and use it in GitHub Desktop.
Save CatTail/6009885 to your computer and use it in GitHub Desktop.
Scope-Safe Constructors
/**
* Code example from <professional javascript for web developers v3 p733>
*/
// problem
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
var person = Person(“Nicholas”, 29, “Software Engineer”);
alert(window.name); //”Nicholas”
alert(window.age); //29
alert(window.job); //”Software Engineer”
// solution
function Person(name, age, job){
if (this instanceof Person){
this.name = name;
this.age = age;
this.job = job;
} else {
return new Person(name, age, job);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment