js实现链式
链式调用的实现原理
链式调用(Method Chaining)允许在一个对象上连续调用多个方法,无需重复引用对象。实现的核心在于每个方法返回对象本身(this)或其他可链式调用的对象。

基础实现示例
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this;
}
subtract(num) {
this.value -= num;
return this;
}
multiply(num) {
this.value *= num;
return this;
}
getResult() {
return this.value;
}
}
// 链式调用
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);
}
subtract(num) {
return new ImmutableCalculator(this.value - num);
}
}
const calc1 = new ImmutableCalculator(10);
const calc2 = calc1.add(5).subtract(3);
console.log(calc1.value); // 10 (原对象未改变)
console.log(calc2.value); // 12
异步链式调用实现
结合Promise实现异步操作的链式调用:
class AsyncTask {
constructor() {
this.promise = Promise.resolve();
}
then(fn) {
this.promise = this.promise.then(fn);
return this;
}
catch(fn) {
this.promise = this.promise.catch(fn);
return this;
}
}
new AsyncTask()
.then(() => fetch('/api/data'))
.then(res => res.json())
.catch(console.error);
链式调用的注意事项
- 中断处理:某些方法可能需要中断链式调用(如返回非
this的值) - 性能影响:频繁创建新对象可能影响性能(如不可变模式)
- 调试难度:过长的链式调用可能增加调试复杂度
常见应用场景
- jQuery的DOM操作:
$('div').addClass('active').hide() - 测试框架断言:
expect(value).toBe(5).not.toBeNull() - 构建器模式:
new QueryBuilder().select().where().orderBy()






