Last active
August 29, 2015 14:05
-
-
Save SeanTRobinson/342299cf22e80ca4c8b2 to your computer and use it in GitHub Desktop.
If somebody forgets to call a constructor with 'new', then 'this' refers to the global scope. When you assign properties within the constructor, you are instead augmenting the global scope. The following pattern helps stop that from happening.
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
function Book(isbn, title, author) { | |
if(this instanceof Book) { | |
this.isbn = isbn; | |
this.title = title; | |
this.author = author; | |
} else { | |
return new Book(isbn, title, author); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment