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 2 of 2
  1. #1
    New Coder
    Join Date
    Jan 2004
    Location
    London, England
    Posts
    95
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Ways of doing things

    Here's two very similar solutions to a the problem of rounding numbers
    Code:
    <html>
    <body>
    <script language="JavaScript" type="text/JavaScript">
    <!-- Hide code from older browsers
    
    function fixedRound(a,n){
                    a= Math.round(a*Math.pow(10,n));
                    a/=Math.pow(10,n);
                    return(a.toFixed(n));
            }
    Number.prototype.toFixedRound= function(n){
                    var N= this;
                    N= Math.round(N*Math.pow(10,n));
                    N/=Math.pow(10,n);
                    return(N.toFixed(n));
            }
    var N=1.13708,n=2;
    str1=N+' Rounded: '+N.toFixedRound(n);
    str2=N+' Rounded: '+fixedRound(N,n);
    alert("1:" + str1 + " 2:" + str2)
    
    -->
    </script>
    </body>
    </html>
    Why would you choose dot-notation over function reference, or vice versa? (I'm not really interested in whether it's a good way of rounding or not )

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    UmeŚ, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    It's more a choice of whether you want it to be a method of the object, and thus available to just that kind of object, or whether you want a generic function. Neither choice can be said to be better than the other without more detail about where and why you need the function/method. Methods are the obvious choice for custom objects, especially if they need access to it's internals.




    This is one aspect that even the language makers aren't consistent at. Why are parseInt, parseFloat etc. global functions and not methods on the Number object? Why is for example String.fromCharCode not a global function in similar vein?
    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


  •  

    Posting Permissions

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