...

View Full Version : toString() Definition Link



nolachrymose
05-31-2004, 02:07 AM
Hello all,

I was working on a library for complex numbers, and discovered something pretty neat (at least, I think so). When I defined the complex.prototype.toString() function, it not only worked when the method itself was called, but it also seemed to be called upon when simply the complex object itself was referenced. Here's an example (I put the toString() method at the top to show what was going on in the background):


complex.prototype.toString = function() {
if(this.imag() == 1)
return this.real() + ' + i';
else if(this.imag() == 0)
return this.real();
return this.real() + ((this.imag() < 0) ?
' - ' + (-this.imag()) + 'i' :
' + ' + this.imag() + 'i');
}

var complex1 = new complex(5,2);
alert(complex1); //alerts '5 + 2i'

Is this a native behavior in ECMAScript? If so, I've never seen it before. It happened in both Firebird 0.8 and IE 6.0, Windows XP.

Happy coding! :)

liorean
05-31-2004, 02:19 AM
In a situation that expects a string value, the toString method is called to turn the object to a string, whether explicitly or implicitly. See: <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/object.html#1193350>

There exists another method like this that is used in other situations, valueOf is used when expecting number, boolean or function. See: <http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/object.html#1193540>

nolachrymose
05-31-2004, 02:22 AM
Man, I should've thought of that when I saw Object.toString()...
Thanks, liorean. :cool:

Happy coding! :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum