0

I'm trying to train myself to write chaining function but got error of

Cannot read property 'minus' of undefined(…)

What's wrong with my code?

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)

1
  • 2
    Your functions don't return anything explicitly. So calling calculator.add(5) will return you undefined which, of course, does not have a .minus. Commented Nov 19, 2016 at 16:33

2 Answers 2

3

You need to return the object (this) in this case, to "chain" like you are expecting

You print() also doesn't return anything so result is always undefined.

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)

Sign up to request clarification or add additional context in comments.

Comments

0

You can also store a reference to the object returned.

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();

2 Comments

why not just use this?
shrug I'm more used to using 'this' when there is a new involved. This snipplet didn't use new.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.