声明var that = this的原因是什么?在javascript

What is the reasoning behind declaring var that = this; in javascript?

本文关键字:是什么 javascript var that this 声明      更新时间:2023-09-26

我在一个新的代码库中遇到过很多次,我想知道它背后是否有任何适当的理由?

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

示例:

$('#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在JavaScript中的含义会根据作用域而变化。构造函数内部的this与函数内部的this的含义有所不同。这里有一篇很好的文章。

如果你想要访问"this"的外部/内部的一个特定的函数调用,其中"this"是什么可能已经改变。这是我能想到的一个例子