Why is Number.toString () not called during string concatenation?

While experimenting with the Object.toString()default behavior of the function , I noticed that string concatenations like the ones below are predictably called toString()for targets:

var x = { toString: () => "one" };
var y = { toString: () => "two" };
var output = 'x is ' + x + ' while y is ' + y;
console.log(output); // writes "x is one while y is two" to the console

However, the same is not observed when toString()redefined in prototypes Numberand Boolean, for example. To obtain the desired result, you must "force" call the call toString():

Number.prototype.toString = () => "42";
Boolean.prototype.toString = () => "whatever you wish";

var a = 1;
console.log('The answer is ' + a); // writes "The answer is 1"
console.log('The answer is ' + a.toString()); // writes "The answer is 42"

var b = true;
console.log('Girl you know it\ ' + b); // writes "Girl you know it true"
console.log('Girl you know it\ ' + b.toString()); // writes "Girl you know it whatever you wish"

This is consistent across browsers (tested on Chrome, Firefox, and Edge), so I assume this is standard behavior. Where is this documented? Is there a list of standard objects that receive special processing during string concatenations?

+4
2

JavaScript .

+, , :

7 lprim be ToPrimitive (lval).

9 rprim be ToPrimitive (rval).

+ .

ToString .

. 7.1.12.1.

... .


:

, .

, .toString, .

+6
    • Type (lprim) String Type (rprim), String,
      • lstr ? ToString (lprim).
      • rstr ? ToString (rprim).
      • - lstr rstr.
  • ToString

    : Number = > Return NumberToString ().

  • NumberToString

    • m NaN, "NaN".
    • m +0 -0, "0".
    • m , - "-" ! ToString (-m).
    • m + ∞, "".

    • ... .

+3

Source: https://habr.com/ru/post/1695312/


All Articles