我发现了JavaScript(或者我的浏览器的想法)的一个特点:
var s = "Hello, world";
function foo(arg)
{
console.log(arg);
console.log(this);
}
foo.call(s, s);
Run Code Online (Sandbox Code Playgroud)
在启用Firebug控制台的情况下运行上述操作,我得到:
Hello, world
String { 0="H", 1="e", more...}
Run Code Online (Sandbox Code Playgroud)
为什么在成为this传递给字符串之前,字符串会自动变成一个奇怪的对象foo?
我称之为奇怪对象的原因是因为jQuery会对它产生影响.例如:
$.each(["one", "two", "three"], function(i, x) {
$('<p></p>').text(x) .appendTo('body'); // Works
$('<p></p>').text(this).appendTo('body'); // Doesn't work
});
Run Code Online (Sandbox Code Playgroud)
this被强制转换成一个对象,即Object("test")在内部调用。
(function() {
return this;
}).call("test");
// returns same as `new String("test")` or `Object("test")`
Run Code Online (Sandbox Code Playgroud)
请注意,使用严格模式确实会返回原始值:
(function() {
"use strict";
return this;
}).call("test") === "test"; // true
Run Code Online (Sandbox Code Playgroud)