箭头函数本身不直接支持链式调用,需通过返回 this 或目标对象实现;在类中作为字段使用时须显式返回 this,避免返回原始值;纯函数场景可用 pipe/compose 模拟链式,但箭头函数无法用 call/apply/bind 改变 this。

箭头函数本身不直接提供链式调用能力,链式调用的关键在于每个方法返回一个对象(通常是当前实例或新实例),而箭头函数可以作为这些方法的实现体参与其中。只要函数返回可继续调用的对象,就能支持链式风格。
让箭头函数返回 this 或目标对象
在类或工具对象中,把箭头函数赋值给属性时,需确保它返回 this(或兼容链式的目标对象),否则调用会中断。
- 普通箭头函数默认不绑定 this,但在类字段中定义时,若明确返回 this,就能延续链式
- 避免返回原始值(如字符串、数字、undefined),否则后续调用会报 “xxx is not a function”
配合类或对象封装实现链式结构
典型做法是用 class 封装状态和操作,每个方法(包括箭头函数形式)返回 this。
示例:class Calculator {
constructor(value = 0) {
this.value = value;
}
add = (n) => {
this.value += n;
return this; // 关键:返回 this 才能链式
};
multiply = (n) => {
this.value *= n;
return this;
};
result = () => this.value;
}
const calc = new Calculator();
console.log(calc.add(5).multiply(2).result()); // 10
纯函数组合场景下的“伪链式”
没有 this 上下文时,可用高阶函数或函数组合模拟链式,例如用 pipe 或自定义链式容器包装箭头函数。
- 借助工具如 Ramda 的 R.pipe 或手写 compose 函数串联多个箭头函数
- 返回新对象而非修改原对象,保持不可变性(如 { data, map, filter } 链式 API)
注意 this 和 call/apply 的限制
箭头函数不能通过 call、apply 或 bind 改变 this,所以在需要动态上下文的链式库中(如 jQuery 风格),优先使用普通函数声明方法。
- 如果必须用箭头函数且需绑定上下文,可在构造时用闭包捕获 this,再返回带 this 的箭头函数
- 多数现代链式设计(如 Lodash FP、D3 selection)已转向函数式组合,弱化 this 依赖

















