I’m fairly new to JavaScript and I’m cleaning up some JavaScript code I downloaded. One of the inconsistencies in this code is mixed usage of both this and the local variable that that references it.
An example code snippet (private method within a jQuery UI widget):
_populateLists: function(options) {
//do stuff with this
var that = this;
options.each(function(index) {
//use both this AND that, they are different in this scope
});
//here this and that are the same thing
//I want to be consistent, is one preferable over the other?
},
In many places throughout the code, where the scope is such that this === that, there is mixed usage, even within the same line of code.
For the sake of readability and maintainability, is it preferable to use this or that?
Note: I realize a lot of these types of things depend on developer preference. But before I decide to rewrite the code to use one over the other, I’d like to understand any reasoning if/why one would be preferred over the other.
EDIT: In this script, I think the only reason this is being assigned to a local variable is so that it can be referred to from within the inner closure.
The reason that the value of
thisis commonly assigned to a local variable is so that you can close over that value and use it inside a nested function.thisis a special variable and somewhat different from normal local variables in that it is automatically set to the object upon which a function was called (if any); otherwise, the global object. However, this intrinsic value ofthisis somewhat muddied by jQuery’s liberal use ofcallandapply, which allow the caller to specify the value ofthis.In a nested function,
thisdoes not inherit the value of its parent’sthisin the same way it would inherit a parent’s local variables through the scope chain.Because of this, we have to stash the value of
thisin a local variable if we need it inside a nested function, such as theeachcallback in your example.Of course, when you’re still in the parent scope,
thiswill still equalthat(orselfor whatever). At first glance, it may seem like there’s no difference between the two, but there is one important performance impact:Minification. If you assign
thisto a local variable, all references to that variable can be reduced to one character. References tothiscannot. Compare this minified output:With 4 references to
this, you save bytes by using a variable. If you have to capturethisfor an inner function anyway, using the local variable instead ofthisin the outer function gets you savings even with a single reference.