Search code examples
javascriptpropertiessingletonprototypal-inheritance

Javascript property access without variable assignment or declaration: Why?


I've inherited a fairly large code-base and there seems to be a bit of a coding pattern going on, but I cannot for the life of me see what it does.

Essentially, the app contains of a number of classes, each with a sort of factory function that enforces singletons. However, there appears to be a redundant line that just accesses an object property without assigning it to a variable, or setting the property.

For example:

myApp.dialog.AddEvent = Backbone.View.extend({
  initialize: function() { ... },
  render: function() { ... },
  refresh: function() { ... }
});

myApp.dialog._addEvent; // <-- What is this for?

myApp.dialog.addEvent = function() {
  var d = myApp.dialog._addEvent;
  if (!d) {
    d = myApp.dialog._addEvent = new myApp.dialog.AddEvent();
  }
  return d;
}

What does the line myApp.dialog._addEvent actually do, if anything? The number of times it appears throughout the app suggests it isn't just a typo. Possibly some kind of property instantiation hack for old IE or something like that?


Solution

  • This line of code:

    myApp.dialog._addEvent;
    

    doesn't do anything. It doesn't cause that property to be defined, it doesn't cause an error if the property doesn't already exist. In fact, there is no difference in the myApp.dialog object before or after that line.

    As you surmise, the author may think that the line in question defines the property on the object (which it doesn't) and predefining the property on the object isn't needed for the code the follows anyway.