Why doesn't the method link keep track of this?

I use Babel to translate the 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 consider the method as a typical JavaScript function and pass it as a parameter ( element.click(fooVar.sayFoo) ), when the method actually executes its lexical this , this is an event object, not an instance of Foo , so this.foo is undefined .

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

I tried to look at the ES6 specification, but could not determine the review rules. Is this weird visibility behavior correct according to spec, or is it a bug somewhere (e.g. in Babel)?

+2
source share
1 answer

Is this correct behavior, although it seems strange?

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

Only arrow functions interpret this differently.

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

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

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

+3
source

Source: https://habr.com/ru/post/1261212/


All Articles