For regular functions, this depends on how the function is called, not where it is written.
There are four rules. From highest priority to lowest:
- new binding:
new Foo()setsthisto the new object being created. - Explicit binding:
call,applyandbindsetthisto the value you pass. A bound function cannot be bound again. Onlynewcan override it. - Implicit binding:
obj.method()setsthistoobj, the object before the dot. If you take the method out, as inconst f = obj.method; f(), this link is lost. - Default binding: a plain call
f()getsundefinedin strict mode. In sloppy mode (non-strict code) it gets the global object.
Arrow functions ignore all four rules. They have no this of their own. They use the this of the surrounding code where they were defined.
Code in classes and modules is always strict. So when a method loses its this there, this is undefined.
- For regular functions,
thisis decided by how the function is called. - The priority is
new, then explicit (call,apply,bind), then implicit (obj.f()), then default. - Default
thisisundefinedin strict mode and the global object otherwise. - Arrow functions take
thisfrom the surrounding code where they were written. - Passing a method as a callback loses its implicit
this.
Read more