Why doesn't a method reference keep track of t

2019-07-07 09:18发布

I am using Babel to transpile an ES2015 class:

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

    sayFoo() {
        console.log(this.foo);
    }
}

This class works exactly as I expect if I say something like fooVar.sayFoo(). However, if I try to treat the method like a typical JavaScript function and pass it as a parameter (element.click(fooVar.sayFoo)), when the method actually runs its lexical this is the event object, not the instance of Foo, so the this.foo is undefined.

Instead, since I specified an instance of Foo, I expected fooVar.sayFoo to be bound to the value of fooVar. I have to write an extra wrapper function for this to work as I expect.

I tried to look through the ES6 spec but couldn't figure out the scoping rules. Is this strange scoping behavior correct according to spec, or is it a bug somewhere (e.g., in Babel)?

1条回答
相关推荐>>
2楼-- · 2019-07-07 09:45

Is this the correct behavior, even though it seems weird?

Yes. Methods are more or less syntactic sugar for functions assigned to prototype properties.

Only arrow functions treat this differently.

Instead of writing a wrapper function, however, you can explicitly bind the instance to the method:

element.click(fooVar.sayFoo.bind(fooVar));

See also How to access the correct `this` / context inside a callback?

查看更多
登录 后发表回答