因为规范是这样规定的。
http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tostring
在这个表中,原始类型的字符串值被定义。只有对于对象才使用
ToPrimitive。
该表告诉我们,一个对象
o
的
ToString
是
ToString( ToPrimitive(o, "string"))
。
规范告诉我们,如果一个对象调用了
ToPrimitive
,我们必须按照以下步骤执行:
1. If PreferredType was not passed, let hint be "default".
2. Else if PreferredType is hint String, let hint be "string".
3. Else PreferredType is hint Number, let hint be "number".
4. Let exoticToPrim be GetMethod(input, @@toPrimitive).
5. ReturnIfAbrupt(exoticToPrim).
6. If exoticToPrim is not undefined, then
a. Let result be Call(exoticToPrim, input, «hint»).
b. ReturnIfAbrupt(result).
c. If Type(result) is not Object, return result.
d. Throw a TypeError exception.
7. If hint is "default", let hint be "number".
8. Return OrdinaryToPrimitive(input,hint).
@@toPrimitive
被设置是一个特殊情况,因此我们现在需要查看 OrdinaryToPrimitive
1. Assert: Type(O) is Object
2. Assert: Type(hint) is String and its value is either "string" or "number".
3. If hint is "string", then
a. Let methodNames be «"toString", "valueOf"».
4. Else,
a. Let methodNames be «"valueOf", "toString"».
5. For each name in methodNames in List order, do
a. Let method be Get(O, name).
b. ReturnIfAbrupt(method).
c. If IsCallable(method) is true, then
i. Let result be Call(method, O).
ii. ReturnIfAbrupt(result).
iii. If Type(result) is not Object, return result.
6. Throw a TypeError exception.
因此,ToPrimitive(o, "string")
的返回值是 o.toString()
,而 toString(o.toString())
与 o.toString()
相同。
toString
方法,它只是一个值。 - Nina ScholzBoolean.prototype.toString()
后,调用true.toString()
返回"1"
。这样就证明了你所说的true
没有toString()
方法是错误的。 - Patrick Robertsprimitive true, instance 1
。这不是你期望的吗? - Mohit BhardwajBoolean.prototype.toString()
后运行true.toString()
,它会返回"1"
而不是"true"
。 - Patrick Roberts