js链式函数实现

链式调用的概念
链式调用(Method Chaining)是一种编程模式,允许在同一个对象上连续调用多个方法。这种模式通过在每个方法中返回对象本身(this)实现,常见于 jQuery、Lodash 等库中。

实现链式调用的核心
- 返回
this:每个方法执行后返回当前对象实例,使得后续方法可以继续调用。 - 支持链式的方法:需确保方法不返回其他值(如
undefined),否则链式调用会中断。
基础实现示例
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this; // 返回this以实现链式
}
subtract(num) {
this.value -= num;
return this;
}
multiply(num) {
this.value *= num;
return this;
}
getResult() {
return this.value; // 终结方法,不返回this
}
}
// 使用示例
const result = new Calculator(10)
.add(5)
.subtract(3)
.multiply(2)
.getResult(); // 输出: 24
高级应用:条件链式
通过返回新实例而非修改原对象,可实现不可变链式:
class ImmutableCalculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
return new ImmutableCalculator(this.value + num);
}
getResult() {
return this.value;
}
}
const calc = new ImmutableCalculator(10);
const newCalc = calc.add(5); // 返回新实例
console.log(calc.getResult()); // 10 (原对象未变)
console.log(newCalc.getResult()); // 15
注意事项
- 终结方法:如
getResult()不应返回this,否则链式无法终止。 - 性能考虑:频繁创建新实例(不可变模式)可能影响性能。
- 错误处理:链式中若某步出错,需通过
try-catch或返回错误对象处理。
实际应用场景
- DOM 操作:如 jQuery 的
$('div').addClass('active').hide()。 - 数据处理:如 Lodash 的
_.chain([1,2,3]).map(n => n*2).sum().value()。 - Builder 模式:构造复杂对象时逐步设置属性。






