Extending Number.prototype in javascript and the Math object?

后端 未结 8 1747
孤城傲影
孤城傲影 2021-02-05 03:11

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

相关标签:
8条回答
  • 2021-02-05 03:22

    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.

    0 讨论(0)
  • 2021-02-05 03:22

    Try doing 123.round();

    Your javascript console will throw a few hundred of errors to your eyes :P, nah ...

    You can do:

    Number.prototype.x then: (123).x(); but never 123.x();

    0 讨论(0)
  • 2021-02-05 03:23

    My view on this is that if you do the proper checks as to not overwrite native functionality, name with understanding of native naming standards and it makes your code more readable and manageable, then make your code comfortable and convenient.

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

    AS for using this, because of the nature of javascript, I believe the best way to do this is by:

    • Wrapping the number in a variable instead of a simple static value (Most often the case)
      • nNum.round();
    • Wrapping the simple static value in parentheses :
      • (123).round();
    • Calling using square bracket notation
      • 123["round"].call();
    0 讨论(0)
  • 2021-02-05 03:23

    You can do this

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

    https://www.w3schools.com/jsref/jsref_prototype_num.asp

    0 讨论(0)
  • 2021-02-05 03:32

    I think Math is more than set of Number methods. It's usage wider. Say, using NumberVariable.PI can be confusing. Same with random numbers generation.

    Also I think extending number is OK, because it's the part of JS nature. Maybe someone will correct me if I am wrong here.

    0 讨论(0)
  • 2021-02-05 03:32

    I believe calling it this way works as well, since Number's prototype functions work just like every other Object's prototype functions do:

    5.5["round"]();
    //should return 6
    
    0 讨论(0)
提交回复
热议问题