Created
July 16, 2013 15:42
-
-
Save CatTail/6009885 to your computer and use it in GitHub Desktop.
Scope-Safe Constructors
This file contains hidden or 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
| /** | |
| * 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