function foobar() {
console.log(this);
}
foobar.call("Hello");
此代码显示:
{ '0': 'H', '1': 'e', '2': 'l', '3': 'l', '4': 'o' }
我期待显示"你好"。
为什么?以及如何补救?
Function#call
(间接地)将字符串原语转换为String
对象(参见规范的§10.4.3;我们从§15.3.4.4开始,它把我们带到§13.2.1,这将我们带到§10.4.3)。
您可以通过以下方式强制将其恢复:
console.log(this.toString());
请注意,在严格模式下,它不会转换为 String
对象,因为在严格模式下,this
可以是基元(包括基元字符串)。 例如:
// Here, it gets converted to an object
function foo() {
snippet.log(typeof this); // "object"
}
foo.call("Hello");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
但是如果我们使用严格模式:
// Strict mode
"use strict";
// Here, it remains a primitive
function foo() {
snippet.log(typeof this); // "string"
}
foo.call("Hello");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
由于call()
函数的第一个参数thisArg
不是null
或undefined
所以函数体内this
的值等于Object(thisArg)
。
在调用函数说明中查看更多内容。