valueOf() vs. toString() in Javascript
在Javascript中,每个对象都有一个值Of()和toString()方法。我本来以为每当需要字符串转换时都会调用toString()方法,但显然它被valueOf()所取代。
例如,代码
var x = {toString: function() {return "foo"; },
valueOf: function() {return 42; }};
window.console.log ("x="+x);
window.console.log ("x="+x.toString());
将打印
x=42
x=foo
这让我感到倒退..例如,如果x是一个复数,我会希望 valueOf() 给我它的大小,但是每当我想转换为字符串时,我都会想要类似“a + bi”的东西。而且我不想在暗示字符串的上下文中显式调用 toString()。
事实就是这样吗?