let obj = {
toString() {
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. Instead it uses the toString() method and alerts 2. Please why is this so?
Since
+obj
requires a number, shouldn't it use thevalueOf()
prototype for type conversion which returns the object.
It actually does call the valueOf
method. But since - as you say - it returns an object, not a primitive value, it is found useless. Then, the alternative is called: toString()
, which does return a primitive value that is subsequently cast to a number.
You can try
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);