当前位置:首页 > JavaScript

js函数实现链式调用

2026-03-01 17:29:53JavaScript

js函数实现链式调用

链式调用的实现原理

链式调用(Method Chaining)的核心是让每个方法返回当前对象(this),使得后续方法可以继续在同一个对象上操作。这种模式常见于 jQuery、Lodash 等库中。

基础实现示例

function Calculator() {
  this.value = 0;

  this.add = function(num) {
    this.value += num;
    return this; // 返回当前对象
  };

  this.subtract = function(num) {
    this.value -= num;
    return this;
  };

  this.result = function() {
    return this.value;
  };
}

// 使用示例
const calc = new Calculator();
const result = calc.add(5).subtract(2).add(10).result();
console.log(result); // 输出: 13

类语法实现(ES6+)

class Calculator {
  constructor() {
    this.value = 0;
  }

  add(num) {
    this.value += num;
    return this;
  }

  subtract(num) {
    this.value -= num;
    return this;
  }

  get result() {
    return this.value;
  }
}

// 使用示例
const result = new Calculator().add(5).subtract(2).add(10).result;
console.log(result); // 输出: 13

支持异步操作的链式调用

通过返回 Promise 并保持链式结构:

class AsyncChain {
  constructor(value = 0) {
    this.value = value;
  }

  asyncAdd(num) {
    return new Promise((resolve) => {
      setTimeout(() => {
        this.value += num;
        resolve(this); // 返回当前对象
      }, 100);
    });
  }

  asyncSubtract(num) {
    return new Promise((resolve) => {
      setTimeout(() => {
        this.value -= num;
        resolve(this);
      }, 100);
    });
  }
}

// 使用示例
new AsyncChain()
  .asyncAdd(5)
  .then(instance => instance.asyncSubtract(2))
  .then(instance => instance.asyncAdd(10))
  .then(instance => console.log(instance.value)); // 输出: 13

链式调用的注意事项

  • 不可变数据:若需保持数据不可变性,应返回新对象而非修改原对象
  • 调试难度:长链式调用可能增加调试复杂度
  • 性能影响:频繁创建新对象可能影响性能(适用于不可变模式)

不可变链式示例

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 result = new ImmutableCalculator()
  .add(5)
  .subtract(2)
  .add(10).value;
console.log(result); // 输出: 13

js函数实现链式调用

标签: 链式函数
分享给朋友:

相关文章

Vue函数实现

Vue函数实现

在Vue中实现函数可以通过多种方式,具体取决于使用场景(选项式API、组合式API或生命周期钩子)。以下是常见方法: 方法1:选项式API中的methods 在Vue 2或选项式API中,函数通常…

vue防抖函数实现

vue防抖函数实现

防抖函数原理 防抖(Debounce)是一种限制函数频繁调用的技术,在事件被触发后延迟执行,若在延迟时间内再次触发,则重新计时。适用于输入框搜索、窗口大小调整等场景。 Vue 中实现防抖的三种方式…

vue中实现节流函数

vue中实现节流函数

使用 Lodash 的 _.throttle 方法 安装 Lodash 并导入 throttle 方法: npm install lodash 在 Vue 组件中使用: import { thro…

react如何调用函数

react如何调用函数

React 函数调用的方法 在 React 中调用函数可以通过多种方式实现,具体取决于函数的作用和调用时机。以下是常见的几种方法: 直接在组件中调用函数 函数可以在组件的 render 方法或…

react函数组件如何更新

react函数组件如何更新

React 函数组件更新方法 使用 useState Hook 通过 useState Hook 可以定义组件的状态,并触发重新渲染。useState 返回一个状态值和一个更新状态的函数。调用更新函数…

react组建中如何调用函数

react组建中如何调用函数

在 React 组件中调用函数的方法 React 组件中调用函数的方式取决于函数的定义位置和作用域。以下是常见的几种方法: 在组件内部定义并调用函数 函数可以直接在组件内部定义,并通过事件或生命周…