箭头函数在ES6类中没有绑定“this”吗? [英] Do arrow functions not bind `this` inside ES6 classes?

查看:151
本文介绍了箭头函数在ES6类中没有绑定“this”吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶,这不行。 (我正在运行 iojs 2.3.0与 - harmony_arrow_functions 标志。)

  class Foo {
constructor(){this.foo =foo; }
sayHi(){return(()=> this.foo)(); }
}
f = new Foo();
f.sayHi //无法读取未定义的属性foo。

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

解决方案

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

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

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

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

BTW:我正在使用 babel p>

I'm surprised this doesn't work. (I'm running iojs 2.3.0 with the --harmony_arrow_functions flag.)

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

I would have expected the arrow function to pick up the right value for this. Am I missing something?

解决方案

I don't know the problem, but my version works fine for me:

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

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

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

BTW: I am using babel

这篇关于箭头函数在ES6类中没有绑定“this”吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆