I like this book, but some of the examples do not fully explain what is happening. Here is an example of a caching function for storing a set of functions:
var store = {
nextId: 1,
cache: {},
add: function(fn) {
if (!fn.id) {
fn.id = store.nextId++;
return !!(store.cache[fn.id] = fn);
}
}
};
function ninja(){}
assert(store.add(ninja),
"Function was safely added.");
console.log('ninja does not have an id property now:',ninja);
assert(!store.add(ninja),
"But it was only added once.");
Most of this is obvious - when store.add (ninja) is called for the first time, the fn parameter does not see the id property, so it adds the store.nextId variable as the id property.
, , - , fn.id store.add(ninja). , ninja store, store.add(ninja) , id, . , ninja store.add , add() , fn id?
- , ?