【问题标题】:What is the reasoning behind declaring var that = this; in javascript? [duplicate]声明 var that = this; 背后的原因是什么?在javascript中? [复制]
【发布时间】:2013-05-23 13:43:38
【问题描述】:

我在我正在查看的新代码库中多次遇到这种情况,想知道它背后是否有任何适当的推理?

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用var that = this; 来保持对当前this 对象的引用,而稍后this 将指向其他对象。

示例 (taken from here):

$('#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
    });
});

【讨论】:

  • 和我的回答一样,但举个例子,玩得很好:)
【解决方案2】:

有时this 在 JavaScript 中的含义会根据作用域而变化。构造函数内部的this 与函数内部的this 不同。这是关于它的good article

【讨论】:

    【解决方案3】:

    如果您想在特定函数调用范围之外/内部访问“this”,其中“this”可能已更改。只是我能想到的一个例子。

    【讨论】:

      猜你喜欢
      • 2011-11-06
      • 2011-07-18
      • 2011-06-20
      • 2017-09-18
      • 1970-01-01
      • 2017-04-23
      • 2010-11-23
      相关资源
      最近更新 更多