newbie
newbie

Reputation: 375

Using a partial function inside a bind for underscore

I have some code that sets the first parameter of the function and another piece of code that sets the second parameter. After the second parameter is set, I need to return a callback function eventually (with the two params set).

var f = function(a,b) { return a-b; }

var g = _.partial(f, 5); 

g(1); // gives 4

var h = _.bind(g, 1); // I want to return h

h(); // but calling h() gives NaN. I was expecting 4

Upvotes: 1

Views: 221

Answers (2)

newbie
newbie

Reputation: 375

Typo in the callback to _.bind()

var h = _.bind(g, {}, 1);

Upvotes: 1

tcigrand
tcigrand

Reputation: 2397

The second parameter in _.bind takes an object that you want to bind the scope to, after that, you can specify arguments for the function.

var f = function(a,b) { return a-b; }

var g = _.partial(f, 5); 

g(1); // gives 4

var h = _.bind(g, {}, 1); // I want to return h

h(); //Now returns 4

Upvotes: 1

Related Questions