绑定函数为null

时间:2015-04-13 05:23:46

标签: javascript

function f() {
  return this.x
}
f = f.bind(null)
f() // undefined
x = 1
f() // 1

我找不到任何与nullundefined绑定无效的页面。在任何地方都写出this成为bind的第一个参数的链接,没有提到例外。某人可以提供某个描述此类行为的链接吗?

3 个答案:

答案 0 :(得分:6)

严格模式和非严格模式之间的行为不同。

在非严格模式下,如果您将thisArg设置为nullundefinedthis将被强制转换为全局对象(window

在严格模式下,this可能是null,您将收到错误。

function f() {
  'use strict';
  return this.x
}
f = f.bind(null)
f() // TypeError: Cannot read property 'x' of null

答案 1 :(得分:2)

在你的例子中调用f()的方式(一个简单的调用)"这个"除非绑定到其他内容,否则引用全局对象(窗口)。非严格模式下的绑定仅适用于truthy值,即忽略绑定到null或undefined并且"这个"仍然被绑在窗户上。

这就是为什么1到x的分配(没有var关键字x是全局的,即window.x)导致函数返回1.注释你的例子:

function f() {
  return this.x
}
f = f.bind(null) // no effect in non-strict mode
f() // returns window.x (undefined)
x = 1 // window.x = 1
f() // returns window.x (1)

绑定到真正有用的东西,例如

function f () { return this.x };
var y = { x: 42 };
var z = f.bind(y);
z(); // 42

但是,如果使用严格模式,则null或未定义的绑定将生效。

function f () { "use strict"; return this.x; }
var z = f.bind(null); z(); // TypeError: Cannot read property 'x' of null
z = f.bind(); z(); // TypeError: Cannot read property 'x' of undefined
z = f.bind({x:42}); z(); // 42
z = f.bind({x:"foo"}); z(); // "foo"

答案 2 :(得分:1)

Link to the paragraph,指定此效果。问题是,false this被全局对象替换而不是绑定时,但是在绑定函数调用时。