Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jun 2002
    Posts
    338
    Thanks
    0
    Thanked 0 Times in 0 Posts

    toString() Definition Link

    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):

    Code:
    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!

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    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/...t.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/...t.html#1193540>
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    Regular Coder
    Join Date
    Jun 2002
    Posts
    338
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Man, I should've thought of that when I saw Object.toString()...
    Thanks, liorean.

    Happy coding!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •