Gamak
Gamak

Reputation: 199

Higher Order functions as a property of an object in Javascript

Why do I get an makeAdder is not a function error here? And how can I accomplish making a property of my Widget object a function that is returned from a higher order function?

    var Widget = { 
           init: function() { 
           var total = this.add2(3); 
           console.log(total); // expect 5
        }, 
        add2: this.makeAdder(2),  
        makeAdder: function(left) { 
          return function(right) { 
             return left + right; 
          };
        }
    };

Widget.init();

Upvotes: 0

Views: 73

Answers (2)

Gamak
Gamak

Reputation: 199

@freedomm-m answered my question best in terms of how I presented it. My Collegue suggested currying, in order to accomplish what I was looking for. I'll include it in case anyone is looking to do something similar.

var Widget = { 
  init: function() { 
    var total = this.add2(3); 
    console.log(total); 
  }, 
  add2: function(val) { 
    return this.add(2)(val);
  },  
  add: function(left) { 
      return function (right) {
        return left + right;
      }
  }
};

Widget.init();

Upvotes: 0

fdomn-m
fdomn-m

Reputation: 28611

It can't find the function as it's not been defined yet.

In add2: this.makeAdder(2) you're calling the function 'makeAdder', not defining it while Widget is still being defined.

Try moving the add2 to later in the process, eg:

var Widget = { 
    init: function() { 
        this.add2 = this.makeAdder(2);
        var total = this.add2(3); 
        console.log(total); // expect 5
    }, 
    makeAdder: function(left) { 
      return function(right) { 
         return left + right; 
      };
    }
};

Upvotes: 1

Related Questions