Da die Spezifikationen so sagt. http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tostring In dieser Tabelle sind die String-Werte von Primitiven definiert. Nur für Objekte ToPrimitive wird verwendet.
Die Tabelle sagt uns, dass ToString
für ein Objekt o
ist ToString(ToPrimitive(o, "string"))
Die Spezifikation sagt uns, dass, wenn ToPrimitive
mit einem Objekt aufgerufen wird, wir diese Schritte folgen müssen:
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
ist ein Sonderfall, so dass wir jetzt OrdinaryToPrimitive
betrachten müssen
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.
Dies bedeutet also, dass der Rückgabewert von ToPrimitive(o, "string")
o.toString()
und toString(o.toString())
ist die gleiche wie o.toString()
.
weil die primitive hat keine Methode 'toString', es ist nur ein Wert. –
@NinaScholz, aber ich dachte, dass ein Wert zu einer Zeichenfolge gezwungen werden musste, wenn es als Schlüssel für ein Objekt verwendet wurde. Nach der Neudefinition von 'Boolean.prototype.toString()' gibt ''true.toString()' ''' '' zurück. Das widerlegt also Ihre Behauptung, dass 'true' keine Methode' toString() 'hat. –
es ist Drucken 'primitiv wahr, Instanz 1'. Ist das nicht das, was Sie erwarten? –