What does 'var that = this;' mean in JavaScript?

前端 未结 6 920
后悔当初
后悔当初 2020-11-22 00:49

In a JavaScript file I saw:

function Somefunction(){
   var that = this; 
   ... 
}

What is the purpose of declaring that and

6条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 01:02

    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;
    };
    

提交回复
热议问题