【问题标题】:Arrow function's lexical scope not behaving as expected [duplicate]箭头函数词法范围未按预期运行[重复]
【发布时间】:2018-06-30 04:32:52
【问题描述】:

箭头函数有一个绑定的词法范围。所以在这段代码中person.person1.sayName() 应该输出HB,但它输出GOT(全局范围)。为什么会这样?

var name = "GOT";
var person = {
   name : "HB",
   sayName : function() { return this.name },
   person1 : {
       name : "WW",
       sayName : () => this.name
    }
};
console.log(person.person1.sayName());

【问题讨论】:

    标签: javascript ecmascript-6 scope arrow-functions


    【解决方案1】:

    行为符合预期。因为是箭头函数,所以调用上下文继承自外层作用域(定义person的块,其中this指的是全局对象),而不是外层object,其中嵌套了person1。调用 sayName 时不会捕获调用上下文,并且(可能是嵌套的)对象初始化器不会创建新范围。

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2020-08-30
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 2020-06-02
      • 2017-10-23
      相关资源
      最近更新 更多