Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 555
chrisfrancis27 Avatar asked Apr 18 '26 03:04

chrisfrancis27


2 Answers

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.

like image 53
jfriend00 Avatar answered Apr 20 '26 18:04

jfriend00


Without seeing the source for myApp.dialog._addEvent, it's impossible to say exactly what happens. Typically a single line containing a variable being accessed will do nothing:

var a = {
    wat: 'wat'
};
a.wat; //this does nothing

However, it's possible that an accessor was written for the property, which could cause side-effects (alternatively you might see __defineGetter__, or Object.defineProperty).

var a = {
    get wat() {
        console.log('wat!');
        return 'wat';
    }
};
a.wat; //this writes 'wat!' to the console

This sort of programming is generally considered bad-practice because it violates the principle of least astonishment.

That said, just because it's bad practice doesn't mean that it's not happening.

like image 41
zzzzBov Avatar answered Apr 20 '26 17:04

zzzzBov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!