Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Ways of doing things

1. ## 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 )

• 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?

•

#### Posting Permissions

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