链式调用的核心是每个方法返回 this 并将方法定义在 prototype 上;需确保继承时方法仍返回 this,终结操作(如 .value())应返回结果而非 this。

JavaScript 中用原型链实现链式调用,核心是让每个方法都返回 this(即当前实例),使后续方法能继续在同一个对象上被调用;同时把方法定义在构造函数的 prototype 上,让所有实例共享行为、形成原型链。
让每个方法返回 this
这是链式调用最基础的要求。如果方法内部修改了实例状态(比如设置属性、累加数值),返回 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;
};
const calc = new Calculator();
calc.add(5).multiply(2).add(1); // 链式调用:value 最终为 11
把方法挂载到 prototype 上
把方法写在 prototype 而非构造函数内部,既节省内存(不重复创建函数),又确保原型链完整,便于继承和扩展:
分析 Java Spring Boot 后端 Controller 代码,自动生成 Markdown 格式的接口文档。当用户说“生成 Java 接口文档”、“生成 API 文档”、“从 Spring 代码生成文档”时触发。
- ✅ 正确:方法在
Calculator.prototype上 → 实例通过原型链访问 - ❌ 错误:在构造函数里写
this.add = function() {...}→ 每个实例都有独立副本,浪费内存,且破坏原型链统一性
支持继承时保持链式能力
子类继承后,也要确保重写或新增的方法返回 this,并正确设置原型链:
立即学习“Java免费学习笔记(深入)”;
function AdvancedCalc() {
Calculator.call(this); // 继承父类初始化
}
AdvancedCalc.prototype = Object.create(Calculator.prototype);
AdvancedCalc.prototype.constructor = AdvancedCalc;
AdvancedCalc.prototype.power = function (exp) {
this.value = Math.pow(this.value, exp);
return this; // 同样返回 this,链不断
};
const adv = new AdvancedCalc();
adv.add(3).power(2).multiply(2); // 有效链式:(0+3)² × 2 = 18
注意返回值类型与边界情况
链式调用不是万能的。有些操作天然不适合链式(如获取结果、判断状态),应设计成“终结方法”,不返回 this:
- 推荐提供
.value()或.end()等方法来提取最终值 - 避免在中间方法中返回原始值(如
return this.value),否则链会中断 - 可考虑 Fluent Interface 设计:只对改变状态的操作返回
this,只读操作返回实际值

















