用JavaScript实现函数链式调用,让你的代码更具可读性和灵活性!

20 min read

好的,这里是一个简单的示例:

function Calculator() {
  this.value = 0;

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

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

  this.multiply = function(num) {
    this.value *= num;
    return this;
  };

  this.divide = function(num) {
    this.value /= num;
    return this;
  };

  this.clear = function() {
    this.value = 0;
    return this;
  };
}

// 使用示例
const calculator = new Calculator();
const result = calculator.add(5).subtract(2).multiply(3).divide(4).clear().value;
console.log(result); // 输出0

在此示例中,我们创建了一个 Calculator 对象,该对象具有可链式调用的一些方法。每次调用方法时,它都会更新对象的状态并返回 this,以便我们可以继续调用其他方法。最后我们可以调用 clear 方法来重置 Calculator 对象的状态,以便我们可以开始新的操作。