什么时候方法 valueOf 可能不存在?

When the method valueOf may be absent?

我有这个代码。而且我不明白它是如何工作的。

let obj = {
    valueOf: function () {
        return {};
    },
    toString: function () {
        return 222;
    }
};

console.log(Number(obj)); //222

据此source,转换算法为:

  1. Call obj[Symbol.toPrimitive](hint) if the method exists,
  2. Otherwise if hint is "string" try obj.toString() and obj.valueOf(), whatever exists.
  3. Otherwise if hint is "number" or "default" try obj.valueOf() and obj.toString(), whatever exists.

这里提示是数字。那为什么叫 obj.toString() 呢?没有obj.valueOf()吗?为什么?什么样的对象有这个方法?我找不到任何关于此的有用信息。

这是另一个例子:

var room = {
  number: 777,

  valueOf: function() { return this.number; },
  toString: function() { return 255; }
};

console.log( +room );  // 777

为什么在这种情况下调用obj.valueOf()?为什么这里有这个方法,而第一个例子中没有呢?它是如何工作的?

来自您引用的文章:

Return types


The only mandatory thing: these methods must return a primitive, not an object.

Historical notes
For historical reasons, if toString or valueOf returns an object, there’s no error, but such value is ignored (like if the method didn’t exist).

在您的第一个代码段中,两种 方法都存在并且已尝试:第一个obj.valueOf(),但自从它return是一个空对象不是原始值,obj.toString()也被称为。

在您的第二个代码段中,obj.valueOf() 已经 return 数字 777,成为结果。