JavaScript 中的 toString():为什么 toString() 仍然被调用,因为 valueOf() 原型用于将对象类型转换为数字

toString() in JavaScript: why does toString() still get called since a valueOf() prototype for type conversion of object to number

let obj = {
    toString() {
        return "2";
    }
};

let n = +obj; 

alert(n);

因为 +obj 需要一个数字,它不应该使用 valueOf() 原型进行类型转换,returns 对象。相反,它使用 toString() 方法和警报 2。请问这是为什么?

您应该通过 parseInt() 函数更改 de toString() 函数以获得 NaN 响应。

let obj = {
    parseInt() {
        return "2";
    }
};

let n = +obj; 

alert(n);

Since +obj requires a number, shouldn't it use the valueOf() prototype for type conversion which returns the object.

它实际上确实调用了valueOf方法。但是因为 - 正如你所说 - 它 return 是一个对象,而不是原始值,所以它被发现是无用的。然后,替代方法被称为:toString(),它 return 一个原始值,随后被转换为一个数字。

你可以试试

const obj1 = {
    valueOf() { console.log("valueOf 1"); return this; },
    toString() { console.log("toString 1"); return "1"; },
};
console.log(+obj1);

const obj2 = {
    valueOf() { console.log("valueOf 2"); return 2; },
    toString() { console.log("toString 2"); return "2"; },
};
console.log(+obj2);