Course contentsShow
← JavaScript
Lesson 554 of 2,72314. The 'this' KeywordFree lesson

Chained Method Calls and 'this'

Explore how 'this' works in method chains where each method returns an object.

Chained Method Calls and 'this'

You'll learn how this remains correctly bound when methods return their parent object for chaining.

The Core Idea

Method chaining works when each method returns an object (often this itself), allowing you to call another method immediately on the result. As long as each method is called with the dot syntax, this inside each method refers to the object before the dot — even when methods are chained together.

How It Works

When you write obj.methodA().methodB(), JavaScript evaluates left-to-right:

  1. obj.methodA() executes — inside it, this is obj
  2. That method returns some object (let's say it returns this, which is obj)
  3. .methodB() is called on that returned object — inside it, this is also obj

Each method call follows the implicit binding rule: the object before the dot becomes this.

Example Pattern

const calculator = {
  value: 0,
  add(n) {
    this.value += n;
    return this; // Returns the calculator object
  },
  multiply(n) {
    this.value *= n;
    return this; // Returns the calculator object
  }
};

calculator.add(5).multiply(3);
console.log(calculator.value); // 15

In add(5), this is calculator. It returns calculator, so multiply(3) also has this as calculator.

Why This Matters

Chaining creates fluent, readable APIs. The key is that each method must return an object (typically this) to continue the chain. If a method returns undefined or a primitive, the chain breaks.

Key Takeaway: In method chains, this inside each method refers to the object returned by the previous call — usually the same object throughout when methods return this.