绑定函数为null

Ser*_*nko 6 javascript

function f() {
  return this.x
}
f = f.bind(null)
f() // undefined
x = 1
f() // 1
Run Code Online (Sandbox Code Playgroud)

我找不到任何关于绑定nullundefined没有效果的页面.它被写入的任何地方都this成为第一个参数的链接bind,没有提到异常.有人可以提供某个描述此类行为的链接吗?

xda*_*azz 7

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

在非严格模式下,如果设置thisArgnullundefined,this将被强制转换为全局对象(window).

在严格模式下,this可能null会出现错误.

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


Ser*_*nko 1

链接到指定此效果的段落。问题是, falseythis不是在绑定时而是在绑定函数调用时被全局对象替换。