js函数实现链式调用
链式调用的实现原理
链式调用(Method Chaining)的核心在于每个方法执行后返回对象本身(this),从而允许连续调用其他方法。这种方式常见于jQuery等库中。
基础实现示例
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(3).result();
console.log(result); // 输出6
类语法实现(ES6+)
class Calculator {
constructor() {
this.value = 0;
}
add(num) {
this.value += num;
return this;
}
multiply(num) {
this.value *= num;
return this;
}
getValue() {
return this.value;
}
}
// 使用示例
const result = new Calculator().add(10).multiply(2).getValue();
console.log(result); // 输出20
异步链式调用
通过返回Promise对象实现异步链式调用:
class AsyncTask {
constructor() {
this.promise = Promise.resolve();
}
then(callback) {
this.promise = this.promise.then(callback);
return this;
}
catch(callback) {
this.promise = this.promise.catch(callback);
return this;
}
}
// 使用示例
new AsyncTask()
.then(() => fetch('/api/data'))
.then(res => res.json())
.catch(err => console.error(err));
注意事项
- 需要确保每个链式方法都返回
this或新的可链对象 - 避免在链式方法中返回undefined
- 对于有状态的操作,需注意方法调用的顺序影响结果
- 在类继承中需正确维护
this的指向
进阶模式:返回新对象
某些场景下更适合返回新对象而非修改原对象:

class ImmutableChain {
constructor(value = 0) {
this.value = value;
}
add(num) {
return new ImmutableChain(this.value + num);
}
getValue() {
return this.value;
}
}
// 使用示例
const result = new ImmutableChain(1).add(2).add(3).getValue();
console.log(result); // 输出6






