verystrongjoe
verystrongjoe

Reputation: 3911

give some explanation about bind() function in JavaScript

I saw the source code in the MSD

// Define the original function with four parameters.
var displayArgs = function (val1, val2, val3, val4) {
    document.write(val1 + " " + val2 + " " + val3 + " " + val4);
}

var emptyObject = {};

// Create a new function that uses the 12 and "a" parameters
// as the first and second parameters.
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");

// Call the new function. The "b" and "c" parameters are used
// as the third and fourth parameters.
displayArgs2("b", "c");

// Output: 12 a b c

I can not understand how this source code is working. Bind function can map parameters automatically? Here, it binds two parameters second times.

Upvotes: 0

Views: 43

Answers (1)

chmod
chmod

Reputation: 64

The first argument is always the this value that you want to pass and the rest of the arguments are arguments to your function. You can pass these arguments partially.

What that means is if you have the partial arguments now and you want to pass the rest of the arguments later when available, you can do that by having this bound function.

HTH.

Upvotes: 1

Related Questions