与JavaScript匿名函数中的"this"对象混淆

Pri*_*ank 2 javascript scope this

嗨,我有以下我试图运行的JavaScript代码.我的目标是掌握thisJavaScript中不同范围和不同类型的调用的含义.

如果你查看下面的代码:我有一个内部匿名函数,它被赋值给innerStuff变量.在那个匿名函数中,这样this指向window对象而不是外部函数对象或其他任何东西.事件虽然它仍然可以访问函数的变量.

无论如何,我不确定,为什么会这样; 但是如果你看下面的代码,我会以后的this形式传递thatinnerStuff它,它可以正常运行并doofus在控制台中打印带有属性的对象.

    var someStuff = {
        doofus:"whatever",
        newF: function()
        {
            var that = this;
            console.log(that);
            var innerStuff = function(topThis){
                console.log(topThis);
            };

            return innerStuff(that);
        }
    }

    someStuff.newF();
Run Code Online (Sandbox Code Playgroud)

现在我只是改变了一点代码.而不是分配它innerStuff,我只是通过调用它直接返回该函数,如下所示:

    var someStuff = {
        doofus:"whatever",
        newF: function()
        {
            var that = this;
            console.log(that);
            return function(that){
                console.log(that);
            }();
        }
    }

    someStuff.newF();
Run Code Online (Sandbox Code Playgroud)

这打印内部匿名函数未定义.是因为that作为参数传递的内容与that外部函数中定义的内容之间存在冲突吗?我认为参数会覆盖可见性.为什么价值不会保留?

这完全令人困惑.

另一方面,如果我没有通过that,而只是使用它,因为可见性存在,结果是正确的和预期的.

我错过了什么?它是变量之间的冲突,存在于相同的范围内吗?有没有一个很好的理由,内部函数this必然会受到window反对?

Bri*_*ell 9

this在JavaScript中引用您调用方法的对象.如果调用函数someObject.functionName(args),this则将绑定到该对象.如果只是调用一个裸函数,就像在中functionName(args),那么this将绑定到该window对象.

newF第二个例子中,你that在内部函数中隐藏变量,但没有将任何内容传递给它,所以它是未定义的.

        var that = this;
        console.log(that);
        return function(that){
            console.log(that);
        }();
Run Code Online (Sandbox Code Playgroud)

您可能需要以下内容,如果您想要的东西与第一个示例相同(传入that内部函数):

        var that = this;
        console.log(that);
        return function(that){
            console.log(that);
        }(that);
Run Code Online (Sandbox Code Playgroud)

或者以下,如果您不想隐藏它并只使用外部函数的绑定:

        var that = this;
        console.log(that);
        return function(){
            console.log(that);
        }();
Run Code Online (Sandbox Code Playgroud)