当字符串成为"this"时,为什么字符串会被删除?

Joe*_*ams 7 javascript

我发现了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)

pim*_*vdb 4

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)

*对值的值进行装箱会分配一个对象实例并将该值复制到新对象中。