当我使用this
将apply
设置为字符串然后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
的一些我不明白的巫术?
答案 0 :(得分:7)
当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
关键字的值。
答案 1 :(得分:2)
引用来自Function.prototype.apply的MDN文章:
为乐趣召唤提供的价值。请注意,这可能不是 是方法看到的实际值:如果方法是函数 非严格模式代码,null和undefined将替换为 全局对象,原始值将加框。
这意味着字符串原语被装入String对象。要提供原始字符串,您必须强制执行严格模式:
(function(){ "use strict"; return this }).apply("hello"); // "hello"