One of the uses of Function.prototype.bind
, according to MDN:
The next simplest use of
bind()
is to make a function with pre-specified initial arguments. These arguments (if any) follow the providedthis
value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called.
Question: Why is undefined
being bound here? It should be the this
value which should have been sent. If the same is happening here, how is undefined
an object?
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 leadingThirtysevenList = list.bind(undefined, 37);
var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]
Because the value of
this
insidelist
doesn't matter (becauselist
doesn't ever referencethis
) but you have to specify argument 0 as something in order to specify argument 1. In other words, you cannot skip positional arguments.It isn’t. In strict mode, the
this
value can be specified as any value — object or primitive, includingundefined
. Outside of strict mode, non-nullish primitives are coerced to objects, i.e. primitives other thannull
andundefined
are wrapped as an object. Ifnull
orundefined
are specified,this
will default to the global object (window
in browsers).