Use the .bind () function for the function and set some parameters as persistent, but not others, JavaScript

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

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

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

addTwo(10); // returns 12

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

I tried to do 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 options to set and leave with .bind ()?

+4
source share
3 answers

_.partial _ , .. addThree = _.partial(multiply, _, 3); . , . , JS.

+3

, no:

bind() , this, , , , .

( .)

+2

. ES6.

In the end, any value (for example null, undefined...) in JavaScript can be used as an argument for the function. To do something like this, you will need something similar to C ++ 11 std::placeholders.

+2
source

Source: https://habr.com/ru/post/1615655/


All Articles