刚在接受采访时被问到这个问题:这个功能能不能归还'对象'吗?
function foo() { return typeof this; }
Run Code Online (Sandbox Code Playgroud)
我说的我不确定但猜到了
foo.bind(undefined)()
Run Code Online (Sandbox Code Playgroud)
可能会回来'undefined'.但是在我的控制台中在家测试它是行不通的.
在严格模式,this将不被强制为一个对象:
'use strict';
function foo() { return typeof this; }
console.log(foo.call('abc'));
console.log(foo.call(5));Run Code Online (Sandbox Code Playgroud)
(但这是一个非常奇怪的尝试,我希望永远不会在严肃的代码中看到它)
thisundefined如果没有调用上下文,也可以处于严格模式:
'use strict';
function foo() { return typeof this; }
console.log(foo());Run Code Online (Sandbox Code Playgroud)
在草率模式下,似乎函数不会被强制转换为对象(虽然基元可以):
function foo() { return typeof this; }
console.log(foo.call(() => 'abc'));Run Code Online (Sandbox Code Playgroud)