I was reading some documentation about the bind()
function in javascript.
One of the examples starts off like this:
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
// Create a function with a preset leading argument
var leadingZeroList = list.bind(undefined, 37);
var list2 = leadingZeroList(); // [37]
So my question is:
What exactly does it means to pass (undefined, 37)
to bind()
here?
It means that you don't want this
to refer to anything in the resulting bound function. In other words, it assures that when you call your bound function, this
will be undefined
. Exactly why you'd do that of course depends on the code; lots of functions don't use this
so it's a way of being tidy.
Note that in non-strict mode, it may be the case that the runtime will substitute the global object (window
in a browser) for undefined
, but I can find no spec that stipulates that behavior. In strict mode, no such substitution is performed.
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