function f() {
return this.x
}
f = f.bind(null)
f() // undefined
x = 1
f() // 1
我找不到任何页面说绑定(bind)到
null
或undefined
没有任何作用。到处都写着this
成为bind
的第一个参数的链接,没有提到异常。有人可以提供指向描述这种行为的地方的链接吗? 最佳答案
在严格模式和非严格模式下,此行为是不同的。
在非严格模式下,如果将thisArg
设置为null
或undefined
,则this
将被强制转换为全局对象(window
)。
在严格模式下,this
可能是null
,您将得到一个错误。
function f() {
'use strict';
return this.x
}
f = f.bind(null)
f() // TypeError: Cannot read property 'x' of null