Thursday, May 2, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  64] [ 7]  / answers: 1 / hits: 24073  / 16 Years ago, sat, march 7, 2009, 12:00:00

I've always wondered why Javascript has the global Math object instead of giving numbers their own methods. Is there a good reason for it?



Also are there any drawbacks (other than efficiency) to doing something like this?:



Number.prototype.round = function(){
return Math.round(this);
};


Just to make clear, I understand that constants like π need somewhere and functions that are applied on more than one number like min/max. The question was mainly concerning methods which only effect a single number such as round, abs, sin, pow, etc.


More From » oop

 Answers
8

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 meant, 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 that someone else might do the same thing. Or worse, for example, define Number.prototype.round as 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 functions?



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 meant to be taken too seriously. I do agree with him that with is very dangerous in an implicit global environment.


[#99879] Sunday, March 1, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;