js

链式调用

链式调用

Posted by OYH on April 21, 2019

实现函数的链式调用

链式调用可使代码量大幅度减少,逻辑集中清晰明了,且易于查看和修改。

const computed = new Computed();
computed
  .add(1)
  .add(1)
  .reduce(1);

1. 构造函数

function Computed(num = 0) {
  this.value = num;
}

2. 实现方法

–返回值为构造函数本身,所以能继续调用原型中的方法

Computed.prototype.add = function(num = 0) {
  this.value += num;
  return this;
};
Computed.prototype.reduce = function(num = 0) {
  this.value -= num;
  return this;
};

3. 链式调用

const computed = new Computed();
computed
  .add(1)
  .add(1)
  .add(1)
  .reduce(1);