首页  >  问答  >  正文

函数通过链式方法

尝试理解链式方法,可以像数学一样,也可以像cheerio/jQuery一样,当事情变得太长时,我会缩短并替换为自己的方法。

//这将帮助我在复杂的方法中获得缩短的方法,并应用于项目

function getValue() {  
    this.add = function(y) {
        return x + y;
    };

    this.mult = function(y) {
        return x * y;
    };

    return this;
};

//不使用new操作符的实例会很有趣

const price1 = getValue(8);
const price2 = getValue(2).add(1);
const price3 = getValue(5).add(3).mult(2);

//不重要,但是推进更远:
const price4 = getValue().add(2).add(2);
const price5 = getValue(5).add(2).add(2);

console.log(price1); // 期望值为8
console.log(price2); // 期望值为3
console.log(price3); // 期望值为16
console.log(price4); // 期望值为4
console.log(price5); // 期望值为9
P粉916553895P粉916553895379 天前580

全部回复(2)我来回复

  • P粉884548619

    P粉8845486192023-09-07 19:35:42

    我通过为y添加默认值来改进了上述代码,以防止在未提供y时结果为“nan”。总体而言,这是一个很好的答案。

    function getValue(x = 0) {
      this.x = x;
      this.add = function(y = 0) {
        this.x += y;
        return this;
      };
      this.mult = function(y = 1) {
        this.x *= y;
        return this;
      };
      this.value = function() {
        return this.x;
      };
      return this;
    };
    
    const price1 = getValue(8).value();
    const price2 = getValue(2).add(1).value();
    const price3 = getValue(5).add(3).mult(2).value();
    const price4 = getValue().add(2).add(2).value();
    const price5 = getValue(5).add(2).add(2).value();
    
    console.log(price1); // 期望输出 8
    console.log(price2); // 期望输出 3
    console.log(price3); // 期望输出 16
    console.log(price4); // 期望输出 4
    console.log(price5); // 期望输出 9

    回复
    0
  • P粉739079318

    P粉7390793182023-09-07 12:11:26

    你需要使用 getValue 函数来接收一个参数 x。此外,你的链式函数应该返回 this。最后,你需要一个函数来解包值,即 value()

    请注意,在 price4 中,你没有传入初始值,所以可以默认为 0

    function getValue(x = 0) {
      this.x = x;
      this.add = function(y) {
        this.x += y;
        return this;
      };
      this.mult = function(y) {
        this.x *= y;
        return this;
      };
      this.value = function() {
        return this.x;
      };
      return this;
    };
    
    const price1 = getValue(8).value();
    const price2 = getValue(2).add(1).value();
    const price3 = getValue(5).add(3).mult(2).value();
    const price4 = getValue().add(2).add(2).value();
    const price5 = getValue(5).add(2).add(2).value();
    
    console.log(price1); // 期望值为 8
    console.log(price2); // 期望值为 3
    console.log(price3); // 期望值为 16
    console.log(price4); // 期望值为 4
    console.log(price5); // 期望值为 9

    回复
    0
  • 取消回复