当我this使用apply然后设置为字符串时,我发现了有趣的输出console.log.这是怎么回事?
在Chrome的Javascript控制台中,
(function(){ return this }).apply("hello");
Run Code Online (Sandbox Code Playgroud)
输出到:
String {0: "h", 1: "e", 2: "l", 3: "l", 4: "o"}
Run Code Online (Sandbox Code Playgroud)
为什么"hello"不像我预期的那样?
有趣的是,检查此输出typeof:
typeof (function(){ return this }).apply("hello");
Run Code Online (Sandbox Code Playgroud)
给了我"object",而不是"string".
我猜这是一些apply我不明白的巫术?
当参数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
Run Code Online (Sandbox Code Playgroud)
参考:http://www.ecma-international.org/ecma-262/5.1/#sec-10.4.3(注意,ThisBinding指的是this函数内部关键字的值).