JavaScript ยท Chapter 43 of 55

JavaScript this Keyword

The `this` keyword refers to the object that is currently executing the function. Its value depends on HOW a function is called, not where it's defined.

In a regular method call, `this` is the object before the dot. In a standalone function call (non-strict mode), `this` refers to the global object. Arrow functions don't have their own `this` โ€” they inherit it from their surrounding scope.

this in methods

`obj.method()` sets `this` to obj inside method. Calling the same function detached from obj loses that binding.

this in arrow functions

Arrow functions capture `this` from their enclosing lexical scope at definition time, which makes them ideal for callbacks inside methods.

Example 1 (javascript)
let obj = {
  name: "Kai",
  greet() { return "Hi " + this.name; }
};
console.log(obj.greet());
Output
Hi Kai

this refers to obj because greet was called as obj.greet().

Example 2 (javascript)
let obj = {
  name: "Kai",
  delayedGreet() {
    let arrow = () => "Hi " + this.name;
    return arrow();
  }
};
console.log(obj.delayedGreet());
Output
Hi Kai

The arrow function inherits this from delayedGreet's scope.

Key points

  • this depends on how a function is called, not where it's defined.
  • In a method call, this refers to the object before the dot.
  • Arrow functions inherit this from their enclosing scope.
  • call(), apply(), and bind() let you explicitly set this.
๐Ÿ’ก Note: Losing 'this' binding (e.g., passing a method as a callback) is one of JS's most common gotchas โ€” arrow functions or bind() fix it.

๐Ÿ“ Quick Quiz

1. What determines the value of `this`?

2. Do arrow functions have their own `this`?

3. Which methods let you explicitly set this?