【问题标题】:Do arrow functions not bind `this` inside ES6 classes? [duplicate]箭头函数不绑定 ES6 类中的“this”吗? [复制]
【发布时间】:2015-06-16 12:58:03
【问题描述】:

我很惊讶这不起作用。 (我正在运行带有--harmony_arrow_functions 标志的iojs 2.3.0。)

class Foo {
  constructor() { this.foo = "foo"; }
  sayHi() { return (() => this.foo)(); }
}
f = new Foo();
f.sayHi // Cannot read property 'foo' of undefined.

我本来希望箭头函数为this 选择正确的值。我错过了什么吗?

【问题讨论】:

    标签: node.js ecmascript-6


    【解决方案1】:

    我不知道问题所在,但我的版本对我来说很好:

    class Foo {
        constructor() {
            this.foo = "foo";
        }
    
        sayHi() {
            return (() => console.log(this.foo))();
        }
    }
    
    const f = new Foo();
    f.sayHi();
    

    顺便说一句:我正在使用babel

    【讨论】:

    • 酷,所以我想它一定只是一个 iojs/V8 错误。
    • 很高兴我找到了这个问题,因为我几周前遇到了同样的问题。我花了一段时间才发现这是一个 V8 问题。因为,确实,使用 babel 它可以工作。现在我又可以安然入睡了。
    【解决方案2】:

    您的 IIFE 正在创建一个新范围。 this 指的是 IIFE 的范围,其中 this.foo 未定义。

    解决这个问题的方法是绑定你的 IIFE。

    class Foo {
        constructor() {
            this.foo = 'foo';
        }
        sayHi() {
            return (() => {
                return this.foo;
            }.bind(this))();
        }
    }
    
    let f = new Foo();
    console.log(f.sayHi()); //foo
    

    【讨论】:

    • 但这是预期的行为吗?我的理解是箭头函数应该从周围的词汇上下文中继承它们的 this 值。
    • 显然不是。我们在JS chatroom 中进行了讨论,显然 V8 中的箭头函数被破坏了。
    • 我在 OP 的代码中没有看到 IIFE(如果你的意思是箭头函数立即执行,那是无关紧要的)
    • @FelixKling 你知道 IIFE 代表什么吗?
    • @FlorianMargaine:是的。
    猜你喜欢
    • 2018-08-01
    • 2016-11-04
    • 2019-02-19
    • 2020-01-04
    • 1970-01-01
    相关资源
    最近更新 更多