当前位置:首页 > 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来实现:

js链式函数实现

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

函数式编程实现链式调用

使用纯函数组合的方式也能实现类似链式调用的效果:

js链式函数实现

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

链式调用的终止方法

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

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

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

相关文章

vue防抖函数实现

vue防抖函数实现

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

react如何在model层写函数调接口

react如何在model层写函数调接口

React 中 Model 层函数调用接口的实现 在 React 应用中,Model 层通常负责数据管理和接口调用。可以通过以下方式组织代码: 创建独立的 API 服务模块 将接口调用封装在单独的…

react闭包实现函数

react闭包实现函数

在 React 中实现闭包函数 闭包在 React 中常用于保存函数作用域内的变量状态,尤其在处理异步操作或事件回调时。以下是几种常见的实现方式: 使用 useCallback 缓存函数 useCa…

用js实现trim函数

用js实现trim函数

使用正则表达式实现 通过正则表达式去除字符串首尾的空白字符(包括空格、制表符、换行符等): function trim(str) { return str.replace(/^\s+|\s+$/…

实现normalize函数js

实现normalize函数js

normalize函数的实现 在JavaScript中,normalize函数通常用于处理字符串的Unicode规范化,或者对数据进行标准化处理。以下是几种常见的normalize函数实现方式: U…

js实现apply函数

js实现apply函数

实现 apply 函数 JavaScript 的 apply 方法是函数原型上的一个方法,用于在特定的作用域中调用函数,并允许以数组形式传递参数。以下是手动实现 apply 的方法: 核心思路…