使用字符串作为函数调用范围

Use a string as a function call scope

本文关键字:函数调用 范围 字符串      更新时间:2023-09-26
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不是nullundefined所以函数体内this的值等于Object(thisArg)

在调用函数说明中查看更多内容。