Have you ever wanted to write JavaScript code that flows like this?
cart
.addItem('Shirt', 2)
.applyDiscount(10)
.calculateTotal()
.checkout();
This clean, readable style is called method chaining or a fluent interface. Let’s learn how to build it!
The Core Idea
Method chaining works when each method returns the object itself, allowing you to immediately call another method on it.
Building a Shopping Cart
Let’s create a shopping cart with chainable methods:
class ShoppingCart {
constructor() {
this.items = [];
this.discount = 0;
}
addItem(name, quantity) {
this.items.push({ name, quantity });
return this; // ← This enables chaining
}
applyDiscount(percent) {
this.discount = percent;
return this; // ← Return the cart instance
}
calculateTotal() {
// Calculation logic here
return this;
}
checkout() {
console.log('Order completed!');
return this;
}
}
const cart = new ShoppingCart();
Why This Works
Each method:
- Performs its action (like adding an item)
- Returns
this(the cart instance) - Allows the next method call
Using Our Chainable Cart
// Without chaining
cart.addItem('Pants', 1);
cart.applyDiscount(15);
cart.checkout();
// With chaining (much cleaner!)
cart
.addItem('Shoes', 1)
.applyDiscount(20)
.checkout();
When to Use Method Chaining
Great for:
- Configuration objects
- Builder patterns
- Any multi-step operations
Avoid when:
- Methods need to return specific values
- Operations are independent
Advanced Tip: Conditional Chaining
applyDiscount(percent) {
if (percent > 0) {
this.discount = percent;
}
return this; // Still chainable
}
Now you can create your own elegant, chainable interfaces in JavaScript!
Post a Comment