当前位置:首页 > JavaScript

js链式函数实现

2026-02-03 03:27:42JavaScript

链式调用的基本原理

链式调用的核心是通过在每个方法中返回对象实例(通常是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

链式调用的终止方法

通常在链式调用最后需要有一个终止方法来获取最终结果:

js链式函数实现

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();

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

相关文章

jquery 函数

jquery 函数

jQuery 函数基础 jQuery 是一个快速、简洁的 JavaScript 库,通过封装原生 JavaScript 功能简化 DOM 操作、事件处理、动画等。核心函数 $() 或 jQuery()…

vue实现链式运动

vue实现链式运动

实现链式运动的思路 链式运动指的是多个动画按顺序依次执行,通常需要在前一个动画完成后触发下一个动画。Vue中可以通过结合CSS过渡、JavaScript动画库或自定义逻辑实现。 使用Vue过渡 +…

vue中实现节流函数

vue中实现节流函数

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

react项目如何定义全局函数

react项目如何定义全局函数

定义全局函数的方法 在React项目中,可以通过以下几种方式定义全局函数,以便在整个应用中复用。 使用全局变量挂载 将函数挂载到window对象上,使其成为全局可访问的函数。这种方式简单直接,但可能…

react如何控制函数组件更新

react如何控制函数组件更新

控制函数组件更新的方法 在React中,函数组件的更新通常由状态(state)或属性(props)的变化触发。以下是几种常见的控制函数组件更新的方法: 使用React.memo进行浅比较 React…

react函数组件如何强制刷新

react函数组件如何强制刷新

强制刷新React函数组件的方法 在React函数组件中,强制刷新通常不推荐直接操作,因为React的设计理念是基于状态和props的自动更新。但在某些特殊情况下,可能需要手动触发更新。以下是几种常见…