Method Chaining
Chain multiple method calls together — return this from methods to enable a fluent, readable interface.
Method Chaining
Method chaining lets you call multiple methods in a single statement. The key is returning this from each method.
Without Chaining
var user = new User('Shaun', 'shaun@example.com');
user.login();
user.incrementScore();
user.incrementScore();
user.logout();
// Four separate lines
With Chaining
var user = new User('Shaun', 'shaun@example.com');
user.login()
.incrementScore()
.incrementScore()
.logout();
// One fluent statement
How It Works
class User {
constructor(name, email) {
this.name = name;
this.email = email;
this.score = 0;
}
login() {
console.log(this.name + ' logged in');
return this; // Returns the instance
}
logout() {
console.log(this.name + ' logged out');
return this;
}
incrementScore() {
this.score++;
console.log(this.name + ' score: ' + this.score);
return this;
}
}
Why return this?
user.login() // Returns the user object
.incrementScore() // Called on the returned user → returns user again
.incrementScore() // Called on the returned user → returns user again
.logout(); // Called on the returned user
// Without return this:
user.login(); // Returns undefined
user.login().logout(); // Error: Cannot call logout on undefined
Real-World Example: jQuery
// jQuery uses method chaining extensively:
$('div').css('color', 'red')
.addClass('active')
.slideDown(300);
Key Takeaways
return thisat the end of methods enables chaining- Chaining makes code more readable and concise
- Each chained call operates on the same object
- Many popular libraries (jQuery, Lodash) use method chaining