JavaScript 'this' Keyword Cheat Sheet

1. Global Context (in non-strict mode)

  • this refers to the global object (i.e., window in browsers).
console.log(this); // window (in browsers)

2. Inside a Function

  • Regular function: this refers to the global object (or undefined in strict mode).
function myFunction() {
  console.log(this); // window (non-strict mode), undefined (strict mode)
}
myFunction();

3. Object Method

  • Method: this refers to the object the method belongs to.
const obj = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
obj.greet(); // 'Alice'

4. Arrow Functions

  • Arrow functions do not have their own this; they inherit it from the surrounding (lexical) context.
const obj = {
  name: 'Bob',
  greet: () => {
    console.log(this.name); // 'this' is inherited from the surrounding context
  }
};
obj.greet(); // undefined (global context)

5. Constructor Functions

  • Constructor functions: this refers to the new object being created.
function Person(name) {
  this.name = name;
}

const person = new Person('Charlie');
console.log(person.name); // 'Charlie'

6. `call()`, `apply()`, and `bind()`

  • call() / apply(): Invoke a function with a specified this value.
function greet() {
  console.log(this.name);
}

const user = { name: 'David' };
greet.call(user); // 'David'
greet.apply(user); // 'David'
  • bind(): Create a new function with this set to a specific value.
const greetUser = greet.bind(user);
greetUser(); // 'David'

7. Class Methods

  • In classes, this refers to the instance of the class.
class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(this.name);
  }
}

const person = new Person('Eve');
person.greet(); // 'Eve'

8. Event Listeners

  • Inside event handlers, this refers to the DOM element the event is attached to.
const button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // button (the element)
});

Common Pitfalls

  1. Arrow functions and this: Arrow functions don't bind their own this.
  2. Strict mode: In strict mode ('use strict'), this is undefined inside regular functions.
  3. Lost context: When passing methods as callbacks, this might not refer to the expected object. Use .bind(), or () => {} in the callback.