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 providedthisvalue 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
thisinsidelistdoesn't matter (becauselistdoesn'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
thisvalue 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 thannullandundefinedare wrapped as an object. Ifnullorundefinedare specified,thiswill default to the global object (windowin browsers).