4

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

window.name = "window";

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

object.method();  // print 'window'

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

4

4 回答 4

3

每当您调用函数时,只需编写func(),this函数内部将指向全局对象。在你的情况下,你写:

nestedMethod();

所以this里面nestedMethod是窗口对象。您可以使用call(或apply)为您的函数调用手动定义上下文:

nestedMethod.call(this);
于 2013-07-09T21:36:51.583 回答
2
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'

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

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

不,不是所有的匿名函数都失去了它们的作用域,所有的函数作用域都绑定到全局对象(如果它们不是用 specific 调用的this,请参见applyand call,请参见下面的示例)!

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'
于 2013-07-09T21:34:43.477 回答
2

像这样调用的任何函数:

someFunction();

将具有全局范围作为this(在非严格模式下)的值。您可以将外部范围存储在局部变量中,或者使用.call()or .apply()

  nestedMethod.call(this);
于 2013-07-09T21:34:47.713 回答
0

你应该像这样声明嵌套函数:

Super.prototype.someFunc = function() {
  this.nestedFunc = function() {}
  //now call it
  this.nestedFunc()
}
于 2021-04-09T11:44:57.767 回答