Extending Number.prototype in javascript and the Math object?

后端 未结 8 1748
孤城傲影
孤城傲影 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:34

    There is no drawback in extending Number.prototype other than confusing other people. What's the point? What is better in using value.round() instead of Math.round(value)?

    There are several good reasons for the Math object:

    1. It works for non-numbers, too: Math.round("5") works whereas value.round() won't work when value is a string (for example, the value of a textbox)
    2. Some members of the Math object don't belong to a "primary" number value, like Math.min() or Math.max(). Or do you want to use it like a.max(b)?
    3. Other members are global and do not belong to a specialized number. Examples are constants like Math.PI or the function Math.random().
    0 讨论(0)
  • 2021-02-05 03:39

    So, the conversation on whether its a good idea or not aside, you can do this fine.

    You can do 123.x() but the interpreter for js is broken (as it doesn't interpret the dot as a message dispatch)

    Weirdly, you can use 123 .x() (with a space between the number and the dot) instead, and it'll work.

    123..also works but that's because you've effectively made a decimal and then dispatching to it

    (typeof 123.) === 'number') // true

    Try:

    Number.prototype.times = function(other) { return this * other }; 3 .times(5);

    in the console.

    0 讨论(0)
提交回复
热议问题