Skip to content

Instantly share code, notes, and snippets.

@SeanTRobinson
Last active August 29, 2015 14:05
Show Gist options
  • Save SeanTRobinson/342299cf22e80ca4c8b2 to your computer and use it in GitHub Desktop.
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.
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