javascript - 为什么这个 MDN 示例在 `undefined` 中使用 `.bind(undefined, 37)` ?

标签 javascript function-binding

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 provided this 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?

因为 listthis 的值无关紧要(因为 list 从来没有引用过 this) 但您必须将参数 0 指定为某物 才能指定参数 1。换句话说,您不能跳过位置参数。

how is undefined an object?

事实并非如此。在 strict mode , this 值可以指定为任何值 —— object 或primitive,包括undefined。在严格模式之外,非空基元被强制转换为对象,即 nullundefined 以外的基元被包装为一个对象。如果指定了 nullundefinedthis 将默认为全局对象(浏览器中的 window)。

关于javascript - 为什么这个 MDN 示例在 `undefined` 中使用 `.bind(undefined, 37)` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35413032/

相关文章:

javascript - 谷歌地图动态设置 map 对象的样式

javascript - ESLint 和 This-Bind 运算符

javascript - 如何避免渲染方法中的绑定(bind)或内联箭头函数

javascript - 将 2D 数组的 2D 网格展平为单个 2D 数组,在 JavaScript 中(功能上?)

javascript - 如何将 UTC 时间字符串转换为本地时区中正确的 moment.js 对象?

javascript,获得第二类

Javascript 正则表达式匹配在实际页面上失败,但正则表达式测试工作得很好

c++ - boost::bind()-类似的东西,但用于函数调用

javascript - 如何柯里化(Currying) jQuery 方法——哪个 `this` 值将传递 jQuery 对象?