Search code examples
javascriptmathprototypebuilt-in

Extending Math object through prototype doesn't work


I try to extend JavaScript Math. But one thing surprised me.

When I tried to extend it by prototype

Math.prototype.randomBetween = function (a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a);
};

In console I have error 'Cannot set property 'randomBetween' of undefined' ...

But if I asigne this function to Math.__proto__

Math.__proto__.randomBetween = function (a, b) {
    return Math.floor(Math.random() * (b - a + 1) + a);
};

Then everything works fine.

Can anybody explain me why it works in this way? I appreciate any help.


Solution

  • Math isn't a constructor, so it doesn't have prototype property:

    new Math(); // TypeError: Math is not a constructor
    

    Instead, just add your method to Math itself as an own property:

    Math.randomBetween = function (a, b) {
        return Math.floor(Math.random() * (b - a + 1) + a);
    };
    

    Your approach with __proto__ works because, since Math is an Object instance, Math.__proto__ is Object.prototype.

    But then note you are adding randomBetween method to all objects, not only to Math. This can be problematic, for example when iterating objects with a for...in loop.