node.js - 箭头函数不在 ES6 类中绑定(bind) `this` 吗?

标签 node.js ecmascript-6

<分区>

我很惊讶这不起作用。 (我正在运行带有 --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 获取正确的值。我错过了什么吗?

最佳答案

我不知道问题所在,但我的版本适合我:

class Foo {
    constructor() {
        this.foo = "foo";
    }

    sayHi() {
        return (() => console.log(this.foo))();
    }
}

const f = new Foo();
f.sayHi();

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

关于node.js - 箭头函数不在 ES6 类中绑定(bind) `this` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868265/

相关文章:

javascript - 如何最好地在 js 上对产品进行排序?

javascript - webstorm: "Element is not exported"警告是什么意思?

eclipse - 有没有办法在 Eclipse IDE 中开发 react ?

javascript - 使用 util.inspect 检查深层对象相等性的优点和缺点

php - Node 与 PHP SQLite 性能对比(270 毫秒对比 70 毫秒)——我做错了什么吗?

javascript - while 循环中的 socket.emit

javascript - 如果值为 true,则通过 splice 删除数组项

node.js - 在node.js中检测系统蓝牙设备是否断开

Node.js + socket.io 确定每个实例的最大客户端数量

javascript - JSON 到 HTML : Make Templates depending on JSON field value (ES6 only)