In a JavaScript file I saw:
function Somefunction(){
var that = this;
...
}
What is the purpose of declaring that
and
Sometimes this
can refer to another scope and refer to something else, for example suppose you want to call a constructor method inside a DOM event, in this case this
will refer to the DOM element not the created object.
HTML
JS
var Person = function(name) {
this.name = name;
var that = this;
this.sayHi = function() {
alert(that.name);
};
};
var ahmad = new Person('Ahmad');
var element = document.getElementById('button');
element.addEventListener('click', ahmad.sayHi); // => Ahmad
Demo
The solution above will assing this
to that
then we can and access the name property inside the sayHi
method from that
, so this can be called without issues inside the DOM call.
Another solution is to assign an empty that
object and add properties and methods to it and then return it. But with this solution you lost the prototype
of the constructor.
var Person = function(name) {
var that = {};
that.name = name;
that.sayHi = function() {
alert(that.name);
};
return that;
};