found drama

get oblique

here is a nice thing you can do with scope-safe constructors

by Rob Friesel

A little JavaScript nugget re: scope-safe constructors:

// 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.

About Rob Friesel

Software engineer by day. Science fiction writer by night. Weekend homebrewer, beer educator at Black Flannel, and Certified Cicerone. Author of The PhantomJS Cookbook and a short story in Please Do Not Remove. View all posts by Rob Friesel →

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*