Garth Marenghi
Garth Marenghi

Reputation: 2037

Why is the object name used in the method of the object instead of this?

In the following piece of code store.nextId and store.cache is used in the add method. I was wondering why not this?

var store = {
  nextId: 1,

  cache: {},

  add: function(fn) {
    if (!fn.id) {
      fn.id = store.nextId++;
      return !!(store.cache[fn.id] = fn);
    }
  }
};

Thanks to everyone who answered my question!

Upvotes: 2

Views: 60

Answers (3)

Alnitak
Alnitak

Reputation: 339786

The author of that code may have a good reason for this, but on the face of it this looks like sloppy, naive coding.

IMHO, functions within a JS object should never depend on the external variable name (or names) by which that object is known.

If the code used this it would be possible to do this:

var storeCopy = store;
store = null;
storeCopy.add(...);      // still works

With the internal reference to store in place this code cannot be modularised for re-use.

Upvotes: 2

ruakh
ruakh

Reputation: 183251

The semantics of using store are slightly different from those of using this, in that if you ever treat store.add as a regular function (e.g., passing it as an argument to a different function), then using store means that the function will still refer to store, whereas using this would instead cause it to refer to the global object.

Of course, the tradeoff is that this add method will always refer to the object currently identified by the variable store, rather than to the object that was originally identified by that variable. Assuming that this method is really always supposed to refer to the same object, a way to get the benefit of both approaches is to use an immediately-invoked function expression:

var store = (function () {
    var store = {
        ...  // exactly as defined in the code you posted, but now 'store'
             // refers to the *local* variable 'store', which can never change
    };
    return store;
})();

That said, it wouldn't surprise me if the author of this code did not have any specific use-case in mind, and simply felt that it was clearer to refer to store as store even inside its methods.

Upvotes: 3

Nicole
Nicole

Reputation: 33197

In this specific case (where you have methods on a names variable that is in scope), either this or store work fine.

I prefer this as it is more portable — you can move the object definition or renamed store and not have to change any code inside of it.

Sometimes, however, you do might see a reason to have a global name. An example is if you are creating a function that you will assign as an event handler where it will be bound to a different object. When a function is bound to a different object, that means this will refer to that other object. If you needed a reference back to store, you would need to use it's global name, or a closure reference. The second is usually preferred, again for portability.

Upvotes: 1

Related Questions