js函数实现链式调用

链式调用的实现原理
链式调用(Method Chaining)的核心是让每个方法返回当前对象(this),使得后续方法可以继续在同一个对象上操作。这种模式常见于 jQuery、Lodash 等库中。
基础实现示例
function Calculator() {
this.value = 0;
this.add = function(num) {
this.value += num;
return this; // 返回当前对象
};
this.subtract = function(num) {
this.value -= num;
return this;
};
this.result = function() {
return this.value;
};
}
// 使用示例
const calc = new Calculator();
const result = calc.add(5).subtract(2).add(10).result();
console.log(result); // 输出: 13
类语法实现(ES6+)
class Calculator {
constructor() {
this.value = 0;
}
add(num) {
this.value += num;
return this;
}
subtract(num) {
this.value -= num;
return this;
}
get result() {
return this.value;
}
}
// 使用示例
const result = new Calculator().add(5).subtract(2).add(10).result;
console.log(result); // 输出: 13
支持异步操作的链式调用
通过返回 Promise 并保持链式结构:
class AsyncChain {
constructor(value = 0) {
this.value = value;
}
asyncAdd(num) {
return new Promise((resolve) => {
setTimeout(() => {
this.value += num;
resolve(this); // 返回当前对象
}, 100);
});
}
asyncSubtract(num) {
return new Promise((resolve) => {
setTimeout(() => {
this.value -= num;
resolve(this);
}, 100);
});
}
}
// 使用示例
new AsyncChain()
.asyncAdd(5)
.then(instance => instance.asyncSubtract(2))
.then(instance => instance.asyncAdd(10))
.then(instance => console.log(instance.value)); // 输出: 13
链式调用的注意事项
- 不可变数据:若需保持数据不可变性,应返回新对象而非修改原对象
- 调试难度:长链式调用可能增加调试复杂度
- 性能影响:频繁创建新对象可能影响性能(适用于不可变模式)
不可变链式示例
class ImmutableCalculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
return new ImmutableCalculator(this.value + num);
}
subtract(num) {
return new ImmutableCalculator(this.value - num);
}
}
// 使用示例
const result = new ImmutableCalculator()
.add(5)
.subtract(2)
.add(10).value;
console.log(result); // 输出: 13







