View Full Version : Ways of doing things

Roy Gardiner
12-08-2006, 05:17 PM
Here's two very similar solutions to a the problem of rounding numbers
<script language="JavaScript" type="text/JavaScript">
<!-- Hide code from older browsers

function fixedRound(a,n){
a= Math.round(a*Math.pow(10,n));
Number.prototype.toFixedRound= function(n){
var N= this;
N= Math.round(N*Math.pow(10,n));
var N=1.13708,n=2;
str1=N+' Rounded: '+N.toFixedRound(n);
str2=N+' Rounded: '+fixedRound(N,n);
alert("1:" + str1 + " 2:" + str2)

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

12-08-2006, 08:35 PM
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?