IT:AD:JScript:Concepts:Closures
<
/callout>
## Example ##
function Book(title) {
var title_;
this.getTitle = function() {
return title_;
};
this.setTitle = function(title) {
title_ = title;
};
// should use the setter in case it does something else than just assign
this.setTitle(title);
}
var book = Book("War and Peace");
Compared to the prototype way:
function Book(title) {
this.title = title;
}
Book.prototype.getTitle = function () {
return this.title;
};
var myBook = new Book('War and Peace');
## Reference ##
Summary
- Closures return a created object
- Closures allow private fields (prototypes based objectscan't)
- Closures are factory functions that return objects
- prototypes based ones are definitions, and need the word 'new'
* Closures are slower:
* Popularised in part by Douglas Crockford