here is a nice thing you can do with scope-safe constructors
¶ by Rob FrieselA little JavaScript nugget re: 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
// here's your scope-safe constructor: | |
function Book(title) { | |
if (this instanceof Book) { | |
this.title = title; | |
} else { | |
return new Book(title); | |
} | |
} | |
// and here's a nice thing you can do with scope-safe constructors: | |
var books = [ | |
'JavaScript: The Definitive Guide', | |
'Professional JavaScript for Web Developers', | |
'JavaScript: The Good Parts', | |
'JavaScript Patterns', | |
'Developing Backbone.js Applications' | |
// etc. | |
]; | |
books.map(Book); |
The crux here is how the scope-safe trick (with instanceof
) turns the constructor into a factory for itself, which allows you to pass it to map
or any similar function where you might want to operate on a whole bunch of items.
Leave a Reply