【问题标题】:Ok i have a task, i need to make something like this: obj.function().function().function() JavaScript好的,我有一个任务,我需要做这样的事情: obj.function().function().function() JavaScript
【发布时间】:2020-09-25 19:46:10
【问题描述】:

这是我的代码

 const Steps= {
                ItemValue: 0,
                GetNumber() {
                    return this.ItemValue;
                },
                Step(){
                    return this.getNumber()++;
                },
                StepBack() {
                    return this.getNumber()--;
                },
                NoStep(){
                    return this.getNumber();
                }
            }

我需要做这样的事情: 这是一个问题的代码

const obj = {...Steps};
obj.Step()
       .Step()
       .StepBack()
       .Step()
       .StepBack()
       .NoStep();

在 c# 中这很容易,但在这里我无法理解,问题出在哪里。 你可以给我建议,如何谷歌它或决定。

【问题讨论】:

    标签: javascript function object


    【解决方案1】:

    要在对象上链接方法,您需要在每个方法中返回该对象,以便在该对象上调用您调用的下一个方法。这个this.getNumber()++ 也将导致SyntaxError

    const Steps = {
      ItemValue: 0,
      GetStep() {
        return this.ItemValue;
      },
      Step() {
        this.ItemValue++;
        return this;
      },
      StepBack() {
        this.ItemValue--;
        return this;
      },
      NoStep() {
        return this;
      }
    }
    
    const obj = {
      ...Steps
    };
    
    obj.Step()
      .Step()
      .StepBack()
      .Step()
      .StepBack()
      .NoStep()
    
    console.log(obj.GetStep())

    【讨论】:

      【解决方案2】:

      使用类的基本思想。每个方法都返回实例。

      class myCode {
        constructor(val) {
          this.value = val || 0;
        }
      
        add(val) {
          console.log("add", this.value, "+", val);
          this.value += val;
          return this;
        }
      
        subtract(val) {
          console.log("subtract", this.value, "-", val);
          this.value -= val;
          return this;
        }
      
        double() {
          console.log("double", this.value, "* 2");
          this.value *= 2;
          return this;
        }
      
        get val() {
          console.log("val");
          return this.value;
        }
      }
      
      const myCodeInstance = new myCode(10)
      myCodeInstance
        .add(2)
        .subtract(4)
        .double();
        
      console.log(myCodeInstance.val);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-01
        • 2014-12-26
        相关资源
        最近更新 更多