带有奇怪输出的单行 - 字符串作为“这个”是怎么回事

One-liner with Strange Output -- What's going on with strings as 'this'?

本文关键字:这个 怎么回事 字符串 输出 单行      更新时间:2023-09-26

当我使用 applythis设置为字符串然后console.log它时,我发现了有趣的输出。怎么了?

在Chrome的Javascript控制台中,

(function(){ return this }).apply("hello");

输出到:

String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}

为什么不像我想象的那样"hello"

有趣的是,使用 typeof 检查此输出:

typeof (function(){ return this }).apply("hello");

给了我"object",而不是"string".

我猜那是一些我不懂的apply魔法?

this 的参数在非严格模式下传递时,它会转换为对象,因此它返回一个字符串对象,该对象不同于字符串值。字符串对象中的每个索引按顺序对应于字符串值的字符。 要将其转换回"普通"字符串,只需在其上调用toString() - 这使它成为您习惯的字符串值。

这在 ES5 严格模式下不会发生(当您在程序或函数的开头插入'use strict'时),因为在该模式下,参数不是强制给对象的,而是直接给出的。

// if you're not passing any arguments, it doesn't matter whether you use apply or call
(function () { return this; }).call("see"); // { 0: "s", 1: "e", 2: "e" }, plus some other special properties
(function () { return this.toString(); }).call("see"); // "see"
(function () { 'use strict'; return this; }).call("see"); // "see", where strict mode is supported

引用:http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3(请注意,ThisBinding是指函数内 this 关键字的值)。

引自 MDN 关于 Function.prototype.apply 的文章:

它的价值为乐趣提供了呼唤。请注意,这可能不是 是方法看到的实际值:如果该方法是 非严格模式代码,null 和未定义将替换为 全局对象和基元值将被装箱

这意味着字符串原语被装箱到 String 对象中。要提供原始字符串,您必须强制实施严格模式:

(function(){ "use strict"; return this }).apply("hello"); // "hello"