Method Chaining (còn gọi Fluent Interface / Cascading): gọi liên tiếp nhiều method trên cùng object trong 1 dòng, nhờ mỗi method trả về this.
Trước khi dùng chaining (lặp lại object)
let sportsCar = new Car();
sportsCar.setDoors(2);
sportsCar.setTopSpeed(250);
sportsCar.setFeulCapacity("600 Litres");
sportsCar.displayCarProps();
Sau khi bật chaining (trả về this)
class Car {
constructor() { this.wheels=4; this.doors=4; this.topSpeed=100; this.feulCapacity="400 Litres"; }
setWheels(w) { this.wheels=w; return this; }
setDoors(d) { this.doors=d; return this; }
setTopSpeed(t) { this.topSpeed=t; return this; }
setFeulCapacity(fc) { this.feulCapacity=fc; return this; }
displayCarProps() { console.log(`Wheels:${this.wheels}, Doors:${this.doors}, Speed:${this.topSpeed}, Fuel:${this.feulCapacity}`); }
}
let sportsCar = new Car()
.setDoors(2)
.setTopSpeed(250)
.setFeulCapacity("600 Litres")
.displayCarProps();
Lợi ích
- Code ngắn gọn, đọc như câu tiếng tự nhiên (fluent).
- Giảm lặp tên biến.
- Phổ biến trong: jQuery, Lodash, D3, Builder pattern.