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() ?
_.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With