How does the this keyword work in JavaScript

· Category: JavaScript

Short answer

this refers to the execution context and its value depends on how a function is called, not where it is defined, except for arrow functions which use lexical binding.

Steps

  1. Implicit binding: obj.method() sets this to obj.
  2. Explicit binding: func.call(context, arg1) and func.apply(context, [args]) set this directly.
  3. Hard binding: func.bind(context) returns a new function with this permanently set.
  4. New binding: new Constructor() creates a new object and binds this to it.
  5. Default binding: In non-strict mode, standalone calls bind this to the global object; in strict mode, this is undefined.

Example

const obj = {
  name: 'Eve',
  greet() { console.log(this.name); }
};
const fn = obj.greet;
fn(); // undefined (default binding)
obj.greet(); // Eve (implicit binding)

Common issues

  • Losing this when passing methods as callbacks; fix with .bind() or arrow functions.
  • DOM event handlers default this to the element unless using arrow functions.