How to avoid multiple variable re-declarations on function outputs in JavaScript

前端 未结 6 1298
生来不讨喜
生来不讨喜 2021-01-24 16:37

Consider the following example

function doSomethingToAVariable(variable){
    return variable + 1
}

function doSomethingToAVariableASecondTime(variable){
    re         


        
6条回答
  •  不知归路
    2021-01-24 17:07

    If you want to chain then you need to return the object instead which will contain the final value

    function variableOperations( initialValue )
    {
      this.value = initialValue;
      this.someOp1 = function(){ this.value += 1; return this; } 
      this.someOp2 = function(){ this.value += 2; return this; } 
    }
    
    var a = new variableOperations(1); //new object
    a.someOp1().someOp2();
    
    alert(a.value); //alerts 4
    

提交回复
热议问题