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)?
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:
See also How to access the correct `this` / context inside a callback?