valueOf() vs. toString() in Javascript
- by brainjam
In Javascript every object has a valueOf() and toString() method. I would have thought that the toString() method got invoked whenever a string conversion is called for, but apparently it is trumped by valueOf().
For example, the code
var x = {toString: function() {return "foo"; },
valueOf: function() {return 42; }};
window.console.log ("x="+x);
window.console.log ("x="+x.toString());
will print
x=42
x=foo
This strikes me as backwards .. if x were a complex number, for example, I would want valueOf() to give me its magnitude (so that zero would become special), but whenever I wanted to convert to a string I would want something like "a+bi". And I wouldn't want to have to call toString() explicitly in contexts that implied a string.
Is this just the way it is?