Function.prototype.bind
的用途之一,根据 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.
问题:为什么这里要绑定(bind)undefined
?它应该是应该发送的 this
值。如果这里发生同样的情况,undefined
怎么会是一个对象?
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]
最佳答案
Why is
undefined
being bound here?
因为 list
中 this
的值无关紧要(因为 list
从来没有引用过 this
) 但您必须将参数 0 指定为某物 才能指定参数 1。换句话说,您不能跳过位置参数。
how is
undefined
an object?
事实并非如此。在 strict mode , this
值可以指定为任何值 —— object 或primitive,包括undefined
。在严格模式之外,非空基元被强制转换为对象,即 null
和 undefined
以外的基元被包装为一个对象。如果指定了 null
或 undefined
,this
将默认为全局对象(浏览器中的 window
)。
关于javascript - 为什么这个 MDN 示例在 `undefined` 中使用 `.bind(undefined, 37)` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35413032/