js链式函数实现
链式调用的基本原理
链式调用的核心是通过在每个方法中返回对象实例(通常是this),使得后续方法可以继续在同一个对象上调用。这种模式常见于jQuery等库中。
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;
}
getValue() {
return this.value;
}
}
// 链式调用示例
const result = new Calculator(10)
.add(5)
.subtract(3)
.multiply(2)
.getValue(); // 输出24
实现异步链式调用
对于需要处理异步操作的链式调用,可以通过返回Promise来实现:

class AsyncChain {
constructor(value) {
this.promise = Promise.resolve(value);
}
then(fn) {
this.promise = this.promise.then(fn);
return this;
}
catch(fn) {
this.promise = this.promise.catch(fn);
return this;
}
}
// 使用示例
new AsyncChain(1)
.then(x => x + 1)
.then(x => x * 2)
.then(console.log); // 输出4
函数式编程实现链式调用
使用纯函数组合的方式也能实现类似链式调用的效果:

const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const add = x => y => x + y;
const multiply = x => y => x * y;
const compute = pipe(
add(5),
multiply(2)
);
compute(10); // 输出30
处理中间状态的链式调用
当需要访问中间状态时,可以通过包装对象来保存状态:
class Chainable {
constructor(value) {
this._value = value;
}
map(fn) {
this._value = fn(this._value);
return this;
}
tap(fn) {
fn(this._value);
return this;
}
value() {
return this._value;
}
}
new Chainable(5)
.map(x => x * 2)
.tap(console.log) // 输出10
.map(x => x + 3)
.value(); // 13
链式调用的终止方法
通常在链式调用最后需要有一个终止方法来获取最终结果:
class QueryBuilder {
constructor() {
this.query = {};
}
select(fields) {
this.query.select = fields;
return this;
}
where(conditions) {
this.query.where = conditions;
return this;
}
build() { // 终止方法
return this.query;
}
}
const query = new QueryBuilder()
.select(['name', 'age'])
.where({ age: { $gt: 18 } })
.build();






