方法链接在javascript中失败

时间:2016-11-19 16:30:39

标签: javascript

我试图训练自己编写链接功能但是错误

Cannot read property 'minus' of undefined(…)

我的代码出了什么问题?



var math = function(){
   var result = 0;
   
   var add = function(param){
     result += param;
   };
   
   var minus = function(param){
     result -= param;
   };
   
   var print = function(){
      console.log(result)
   };
   
   return {add:add, minus: minus, print:print};
}

var calculator = math();
var result = calculator.add(5).minus(1).print();
console.log(result)




2 个答案:

答案 0 :(得分:3)

在这种情况下,您需要将对象(this)返回到"链"就像你期待的那样

print()也不会返回任何内容,因此result始终未定义。



var math = function(){
   var result = 0;
   
   var add = function(param){
     result += param;
     return this;
   };
   
   var minus = function(param){
     result -= param;
     return this;
   };
   
   var print = function(){
      console.log('result: ' + result);
      // print doesnt return anything, it needs to if you want to assign anything by calling it
      return result;
   };
   
   return {add:add, minus: minus, print:print};
}

var calculator = math();
var result = calculator.add(5).minus(1).print();
console.log(result)




答案 1 :(得分:0)

您还可以存储对返回对象的引用。



var math = function() {
  var result = 0;

  var add = function(param) {
    result += param;
    
    return math;
  };

  var minus = function(param) {
    result -= param;
    
    return math;
  };

  var print = function() {
    console.log(result)
  };
  
  var math = {
    add: add,
    minus: minus,
    print: print
  };
  
  return math;
}

var calculator = math();
calculator.add(5).minus(1).print();