在javascript中使用"that"关键字

Ayu*_*man 14 javascript

我有很少的javascript广泛使用关键字"那".我看到很多帖子都在谈论javascript关键字"this".

我想在javascript上下文中理解这个关键词的含义,以及它的可见性/范围.

就像是

that.someFunctionaName(someParameter)
Run Code Online (Sandbox Code Playgroud)

这是什么意思?

我理解关键字"this"始终指向当前对象的所有者.

Ben*_*enM 22

that不是JavaScript中的关键字.我怀疑你所拥有的代码正在使用类中的某些东西来定义它自己的实例.例如:

function myClass()
{
    var that = this;
}
Run Code Online (Sandbox Code Playgroud)

通过这样做,您可以确保引用对象,而不是另一个元素.例如,请考虑以下示例:

function myClass()
{
    var that = this;
    $('.myele').click(function() {  

        // 'this' refers to the element that was clicked.
        // 'that' still refers to the myClass() object.
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 另一个相当常用的变量是`self`,遵循相同的逻辑. (4认同)