繁体   English   中英

Javascript嵌套函数丢失范围

[英]Javascript nested function losing scope

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

window.name = "window";

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

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

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

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

nestedMethod();

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

nestedMethod.call(this);
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'

保存对象的作用域——或者使用对象本身!

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

不,并不是所有的匿名函数都失去了作用域,所有的函数作用域都绑定到全局对象(如果它们没有被特定的this call ,请参阅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'

任何像这样调用的函数:

someFunction();

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

  nestedMethod.call(this);

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

Super.prototype.someFunc = function() {
  this.nestedFunc = function() {}
  //now call it
  this.nestedFunc()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM