Are functions with `this` arrows working inside ES6 classes?

I am surprised that this does not work. (I am running iojs2.3.0 with the flag --harmony_arrow_functions.)

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

I would expect the arrow function to pick the right value for this. Did I miss something?

+4
source share
2 answers

I don't know the problem, but my version is great for me:

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

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

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

By the way: I use babel

+2
source

Your IIFE creates a new area. thisthen refers to the IIFE region, where this.foois undefined.

How you get around this binds your IIFE.

class Foo {
    constructor() {
        this.foo = 'foo';
    }
    sayHi() {
        return (() => {
            return this.foo;
        }.bind(this))();
    }
}

let f = new Foo();
console.log(f.sayHi()); //foo
0
source

All Articles