当前位置:首页 > 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();

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

相关文章

jquery函数

jquery函数

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

php 函数实现

php 函数实现

PHP 函数实现基础 PHP 函数的定义使用 function 关键字,后跟函数名和参数列表。函数名不区分大小写,但建议保持一致。 function functionName($param1, $p…

react如何使用函数

react如何使用函数

使用函数组件的基本语法 在React中,函数组件是通过JavaScript函数定义的组件。函数接收props作为参数,并返回React元素。 function Welcome(props) {…

vue实现函数曲线

vue实现函数曲线

Vue 实现函数曲线的方法 在 Vue 中实现函数曲线通常需要结合 HTML5 的 Canvas 或 SVG 技术,以及 JavaScript 的数学计算能力。以下是几种常见的方法: 使用 Canv…

vue实现异步函数

vue实现异步函数

Vue 中实现异步函数的几种方法 使用 async/await 在 Vue 方法或生命周期钩子中可以直接使用 async/await 语法处理异步操作。这种方式代码更清晰,易于理解。 method…

vue组件实现函数调用

vue组件实现函数调用

实现 Vue 组件函数调用的方法 在 Vue 组件中实现函数调用可以通过多种方式完成,以下是常见的几种方法: 通过 methods 定义并调用函数 在 Vue 组件的 methods 选项中定…