In a JavaScript file I saw:
function Somefunction(){
var that = this;
...
}
What is the purpose of declaring that
and
This is a hack to make inner functions (functions defined inside other functions) work more like they should. In javascript when you define one function inside another this
automatically gets set to the global scope. This can be confusing because you expect this
to have the same value as in the outer function.
var car = {};
car.starter = {};
car.start = function(){
var that = this;
// you can access car.starter inside this method with 'this'
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to the global scope
// 'this.starter' is undefined, so we use 'that' instead.
that.starter.active = true;
// you could also use car.starter, but using 'that' gives
// us more consistency and flexibility
};
activateStarter();
};
This is specifically a problem when you create a function as a method of an object (like car.start
in the example) then create a function inside that method (like activateStarter
). In the top level method this
points to the object it is a method of (in this case, car
) but in the inner function this
now points to the global scope. This is a pain.
Creating a variable to use by convention in both scopes is a solution for this very general problem with javascript (though it's useful in jquery functions, too). This is why the very general sounding name that
is used. It's an easily recognizable convention for overcoming a shortcoming in the language.
Like El Ronnoco hints at Douglas Crockford thinks this is a good idea.