'var that = this'是什么意思 在JavaScript中的意思是?
在我看到的JavaScript文件中:
function Somefunction(){
   var that = this; 
   ... 
}
  什么是声明的目的that并将其分配给this ? 
我将以一个例子开始这个答案:
var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
    // this is a reference to the element clicked on
    var that = this;
    colours.forEach(function() {
        // this is undefined
        // that is a reference to the element clicked on
    });
});
我的答案最初是用jQuery来展示的,它只是略有不同:
$('#element').click(function(){
    // this is a reference to the element clicked on
    var that = this;
    $('.elements').each(function(){
        // this is a reference to the current element in the loop
        // that is still a reference to the element clicked on
    });
});
  因为当您通过调用新函数来更改范围时, this频繁更改,因此无法通过使用它来访问原始值。  它走样that允许你还是访问的原始值this 。 
  就个人而言,我不喜欢使用that作为别名。  这很少显而易见,特别是如果功能比几行更长。  我总是使用更具描述性的别名。  在我上面的例子中,我可能会使用clickedEl 。 
来自Crockford
按照惯例,我们做一个私有变量 。 这用于使对象可用于私有方法。 这是为在ECMAScript的语言规范的错误这将导致此不正确地对内部函数来设置一种解决方法。
JS小提琴
function usesThis(name) {
    this.myName = name;
    function returnMe() {
        return this;        //scope is lost because of the inner function
    }
    return {
        returnMe : returnMe
    }
}
function usesThat(name) {
    var that = this;
    this.myName = name;
    function returnMe() {
        return that;            //scope is baked in with 'that' to the "class"
    }
    return {
        returnMe : returnMe
    }
}
var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + 'rn' +
      "UsesThis thinks it's called " + usesthis.returnMe().myName);
这警报...
用途那认为它叫Dave
UsesThis认为它被称为undefined
  这是使内部函数(在其他函数内部定义的函数)更适合工作的一种手段。  在JavaScript中,当你在另一个函数中定义一个函数时, this自动设置为全局范围。  这可能会让你感到困惑,因为你期望this具有与外部函数相同的值。 
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();
};
  当你创建一个函数作为一个对象的方法时(例如car.start ),然后在该方法内部创建一个函数(如activateStarter )时,这是一个特别的问题。  在顶层方法中, this指向的是它的方法(在这种情况下是car )的方法,但是在内部函数中, this现在指向全局范围。  这是一个痛苦。 
  在两个范围内创建一个按惯例使用的变量是javascript这个非常普遍的问题的解决方案(尽管它在jquery函数中也很有用)。  这就是为什么很一般名曰that被使用。  这是克服语言缺陷的容易识别的惯例。 
就像El Ronnoco暗示道格拉斯克罗克福德认为这是个好主意。
链接地址: http://www.djcxy.com/p/17055.html