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:
obj.methodA()executes — inside it,thisisobj- That method returns some object (let's say it returns
this, which isobj) .methodB()is called on that returned object — inside it,thisis alsoobj
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.