4

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?

Alan O'Donnell
  • 1,276
  • 9
  • 17

2 Answers2

2

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

marcel
  • 2,967
  • 1
  • 16
  • 25
  • Cool, so I guess it must just be an iojs/V8 bug. – Alan O'Donnell Jun 16 '15 at 13:25
  • Glad I found this question, because I ran into the same issue weeks ago. It took me a while to find out that it is a V8 issue. Because, indeed, with babel it works. Now I can sleep peacefully again. – kernel Jul 02 '15 at 14:29
0

Your IIFE is creating a new scope. this is then referring to the scope of the IIFE where this.foo is undefined.

The way you'd get around this is by binding your IIFE.

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

let f = new Foo();
console.log(f.sayHi()); //foo
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80