简体   繁体   中英

Why doesn't a method reference keep track of this?

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 (eg, in Babel)?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM