4

I found interesting output when I set this to a string using apply and then console.log'd it. What's up?

In Chrome's Javascript console,

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

Outputs to:

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

Why isn't it "hello" like I would have expected?

Interestingly, checking this output with typeof:

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

Gives me "object", instead of "string".

I'm guessing that is some wizardry with apply that I don't understand?

4

2 回答 2

7

当 for 的参数以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(注意是ThisBindingthis函数内部关键字的值)。

于 2013-10-29T05:27:20.467 回答
2

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

这为有趣的呼吁提供了价值。请注意,这可能不是方法看到的实际值:如果方法是非严格模式代码中的函数,null 和 undefined 将被替换为全局对象,原始值将被装箱

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

(function(){ "use strict"; return this }).apply("hello"); // "hello"
于 2013-10-29T05:37:05.273 回答