Javascript 权威指南:对象转字符串步骤混淆

Javascript the Definitive Guide: the confusion of steps of converting object to a string

根据《权威指南》第 6 版 Javascript 书中的第 3.8.3 节:

To convert an object to a string, JavaScript takes these steps:
• If the object has a toString() method, JavaScript calls it. If it returns a primitive value, JavaScript converts that value to a string (if it is not already a string) and returns the result of that conversion. Note that primitive-to-string conversions are all well-defined in Table 3-2.

• If the object has no toString() method, or if that method does not return a primitive value, then JavaScript looks for a valueOf() method. If the method exists, JavaScript calls it. If the return value is a primitive, JavaScript converts that value to a string (if it is not already) and returns the converted value.

• Otherwise, JavaScript cannot obtain a primitive value from either toString() or valueOf(), so it throws a TypeError.

例如:

var obj = {
    toString: function() {
        console.log('toStirng...');
        return 90;
    },
    valueOf: function() {
        console.log('valueOf...');
        return 80;
    }
}

console.log(obj + '');

因此,上面的代码片段会将 obj 转换为字符串,因为 obj + '',因此它应该打印:

toString...
90

但实际上,它打印:

valueOf...
80

怎么了? obj + '' 不会将 obj 转换为字符串吗?

this 文章中很好地说明:

因为+''利用了ToPrimitive(Number)内部方法。如果您 运行 String(obj) 您将收到 toString 方法结果。