Javascript 嵌套函数失去作用域

pet*_*ter 7 javascript binding scope

有人可以解释一下以下代码的范围绑定吗

window.name = "window";

object = {
       name: "object",
       method: function() {
             nestedMethod: function() {
                   console.log(this.name);
             }
             nestedMethod();
       }
}

object.method();  // print 'window'
Run Code Online (Sandbox Code Playgroud)

我认为我的问题更多是关于this......为什么this会失去范围并默认为全局范围?我们创建的所有匿名函数都会在全局范围内吗?

Nic*_*ngo 3

window.name = "window";

object = {
    name: "object",
    method: function () {
        var self = this;
        var nestedMethod = function () {
            console.log(self.name); // or object.name without declaring self
        }
        nestedMethod();
    }
}

object.method(); // print 'object'
Run Code Online (Sandbox Code Playgroud)

保存对象的范围 - 或使用对象本身!

我们创建的所有匿名函数都会在全局范围内吗?

不,并非所有匿名函数都会失去其作用域,所有函数作用域都绑定到全局对象(如果不使用特定调用它们this,请参阅applycall,请参阅下面的示例)!

window.name = "window";

object = {
    name: "object",
    method: function () {
        var nestedMethod = function () {
            console.log(this.name);
        }
        nestedMethod.call(this); //change the this arg in the current object scope
        // when you call this function with .call(this) you are changing the value of the nestedMethod's this to the current this, which is object
    }
}

object.method(); // print 'object'
Run Code Online (Sandbox Code Playgroud)