CodePark/ questions / this & binding
START PRACTICINGPRACTICE
Frontend question · JavaScript › this & binding

How is the value of this determined in JavaScript?

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() sets this to the new object being created.
  • Explicit binding: call, apply and bind set this to the value you pass. A bound function cannot be bound again. Only new can override it.
  • Implicit binding: obj.method() sets this to obj, the object before the dot. If you take the method out, as in const f = obj.method; f(), this link is lost.
  • Default binding: a plain call f() gets undefined in 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, this is decided by how the function is called.
  • The priority is new, then explicit (call, apply, bind), then implicit (obj.f()), then default.
  • Default this is undefined in strict mode and the global object otherwise.
  • Arrow functions take this from the surrounding code where they were written.
  • Passing a method as a callback loses its implicit this.