Extending Number.prototype in javascript and the Math object?

后端 未结 8 1765
孤城傲影
孤城傲影 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: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();

提交回复
热议问题