链式调用的核心是每个方法返回this并挂载到原型链,支持连续调用;工厂函数可避免原型污染;继承时子类方法须保持return this以维持链式;需注意漏返this、混用非链式方法及异步处理等陷阱。

核心思路是让每个方法都返回当前实例(this),并确保所有方法都可通过原型链访问,从而支持连续调用。
1. 构造函数 + 原型方法定义
把所有链式方法挂载到构造函数的 prototype 上,每个方法末尾返回 this:
function Calculator() {
this.value = 0;
}
Calculator.prototype.add = function(n) {
this.value += n;
return this; // 返回实例本身
};
Calculator.prototype.multiply = function(n) {
this.value *= n;
return this;
};
Calculator.prototype.getValue = function() {
return this.value;
};
// 使用
const calc = new Calculator();
console.log(calc.add(5).multiply(2).getValue()); // 10
2. 避免污染原生原型,封装为工厂函数
更安全的做法是用工厂函数隐藏构造细节,返回已配置好原型链的对象:
function createCalculator() {
const state = { value: 0 };
return {
add(n) {
state.value += n;
return this;
},
multiply(n) {
state.value *= n;
return this;
},
getValue() {
return state.value;
}
};
}
// 使用
console.log(createCalculator().add(3).multiply(4).getValue()); // 12
这种方式不依赖 new 和显式原型链,但本质仍是利用对象方法返回自身实现链式调用。
3. 支持继承与扩展的链式 API
若需子类复用并扩展链式能力,可基于原型链继承,并在子类方法中保持 return this:
function AdvancedCalc() {
Calculator.call(this);
}
AdvancedCalc.prototype = Object.create(Calculator.prototype);
AdvancedCalc.prototype.constructor = AdvancedCalc;
AdvancedCalc.prototype.power = function(n) {
this.value = Math.pow(this.value, n);
return this;
};
const adv = new AdvancedCalc();
console.log(adv.add(2).power(3).getValue()); // 8
关键点:子类方法不能返回新实例(除非刻意设计“不可变链式”),否则会中断原型链上的方法访问。
4. 注意事项与常见陷阱
链式调用看似简单,但容易出错:
- 每个方法必须显式 return this,漏写就断链
- 避免在链中混用非链式方法(如直接返回值的
getValue()应只放在末尾) - 异步操作(如
then())需特殊处理,普通同步链式无法等待 Promise - 不要在原型上修改内置对象(如
Array.prototype),会引发兼容性和维护问题


















