Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use .bind() on a function and set some parameters as constant but not others, JavaScript

Tags:

javascript

I know this is possible using basic closures, but I want to see how to do it with .bind() to better understand this function method. See this example code:

function add (a, b) {
  return a + b;
}

var addTwo = multiply.bind(this, 2);

addTwo(10); // returns 12

This appears to work fine. However, is it possible to use .bind() to do the same thing, but set the second parameter to a fixed value, while leaving the first parameter untouched?

I attempted the following:

function add (a, b) {
  return a + b;
}

var addThree = multiply.bind(this, null, 3);

addThree(10); // returns 10, presumably because null + 10 === 10

Is there a way to pick and choose which parameters to set and which to leave using .bind() ?

like image 235
jmancherje Avatar asked Mar 14 '23 04:03

jmancherje


1 Answers

_.partial does achieve this with _ as the placeholder, i.e. addThree = _.partial(multiply, _, 3); its implementation involves keeping track of the positions of the partial placeholders. While it is a great read, it does involve a library. It is currently the closest thing to having positional argument binding in JS.

like image 137
Brian Avatar answered Mar 16 '23 18:03

Brian