Javascript Fundamentals · Interview Fundamentals

The this keyword

this binding

The this keyword

const counter = {
  count: 0,
  increment() {
    this.count += 1;
  },
};
counter.increment(); // this === counter

That call updates counter.count. Detach the same function and call it on its own, and it breaks — the function and the object were never tied together. What this means depends on how the function is called, not where it was written. Four rules decide it, checked in order:

  • new — new Fn() binds this to the freshly created object.
  • Explicit — fn.call(obj), fn.apply(obj), or fn.bind(obj) bind this to obj.
  • Implicit — obj.method() binds this to obj (the object to the left of the dot).
  • Default — a plain fn() call binds this to undefined in strict mode (the global object otherwise).

Arrow functions are the exception: they have no this of their own. They capture this from the enclosing scope, and call/apply/bind cannot change it. That is why an arrow callback inside a method still sees the method's this.

Losing the receiver is the classic bug: passing obj.method as a callback detaches it, so this becomes undefined. Fix it with obj.method.bind(obj) or an arrow wrapper.

You are about to answer a short quiz on this binding.

  1. Arrow functions have no this of their own; they capture it from the enclosing scope.
  2. Calling obj.method() binds this to ___.
  3. fn.call(obj) and fn.bind(obj) can rebind this inside an arrow function.
  4. In strict mode, a plain function call fn() binds this to ___.
  5. this is decided by how a function is called, not where it is defined.
  6. Passing obj.method as a callback loses its receiver; fix it with obj.method.___(obj).
  7. new Fn() binds this to the newly created object.