Javascript 4.8 Ninja List Secrets - How does this property refer?

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,                                        //#1
    cache: {},                                        //#2
    add: function(fn) {                               //#3
      if (!fn.id) {                                   //#3
        fn.id = store.nextId++;                       //#3
        return !!(store.cache[fn.id] = fn);           //#3
        // not a fan of the above construct - I think the following is clearer:
        // store.cache[fn.id] = fn;
        // return true;
      }                                               //#3
    }
  };

  function ninja(){}

  assert(store.add(ninja),                            //#4
         "Function was safely added.");               //#4
  console.log('ninja does not have an id property now:',ninja);
  assert(!store.add(ninja),                           //#4
         "But it was only added once.");              //#4

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?

- , ?

+4
1

, .

store.add(ninja) ninja id.

DEMO

console.dir(ninja) ( console.log), /

+3

All Articles