The reason for the Math
object is simple: "because Java does it". Not the best of reasons, but here we are. I guess things made more sense back then, before Douglas Crockford started his campaign to suppress half the language*. Originally you were "allowed", or ment, to do things like this:
with (Math) {
var n = min( round(a) * round(b), sqrt(c) );
var result = exp( n + d );
}
The drawback to extending Number.prototype
is: What if someone else does the same thing? Or worse: What if someone else, who's library/script is included on the same page, decides that Number.prototype.round
should be, say, a symmetrical rounding function?
If you are looking for ways to make your life easier, why stop there? Why not simply include Math
functions as global funtions?
var m = 'abs acos asin atan atan2 ceil cos exp floor log max min ' +
'pow random round sin sqrt tan PI').split(' ');
for (var i=0,l=m.length; i<l; i++) {
window[ m[i] ] = Math[ m[i] ];
}
This will drop all the math functions into the global scope, effectively allowing you to stop typing "Math." Ask yourself: Is there any real difference between extending number and extending window with these functions?
* Before you flame me: The Crockford comment is not ment to be taken to seriously. I do agree with him that with
is very dangerous in an implicit global environment.