取而代之的字符串是对象为什么此转换成对象
String.prototype.foo = function() { return this; };
typeof "hello".foo() // object ???
"hello".foo().toString(); //hello
它应该返回字符串而不是我想。
取而代之的字符串是对象为什么此转换成对象
String.prototype.foo = function() { return this; };
typeof "hello".foo() // object ???
"hello".foo().toString(); //hello
它应该返回字符串而不是我想。
第一个真正的字符串("hello"
,'booya'
)是一种原始的价值 - 它不具有任何功能或任何东西。这只是一个价值。
当你做"string".foo
,它会变成这样:
Object("string").foo
里面的foo
,this
点向Object("string")
,而不是原始值。做Object("string")
把它变成一个对象,所以typeof object === 'object'
。
如果你想在 “底层” 原始的,叫valueOf
:
String.prototype.foo = function() {
return typeof this.valueOf();
}
"meep".foo(); //string
它是否记录在某个地方像ECMA规范等? –
@MuhammadShoaib参见[here](http://es5.github.com/#x8.7.1),第二个列表。有趣的是,它看到它创建了一个垃圾收集对象,所以在调用之后它并不存在。所以:'var string =“string”; string.meep = 4; console.log(string.meep);'logs'undefined'。 – Zirak
当您在字符串文字(或任何其他文字)上调用方法时,它将在内部转换为String
对象(或相应的对象)。这就是this
所指的,因此返回值是一个对象。
类型的任何对象是object
,不管它是什么类型的对象:
typeof new String('foo');
// "object"
的toString将对象转换为字符串。它按预期工作。 –
有趣的是,注意typeof“hello”.foo是函数。 –