Extending Math object through prototype doesn't work

前端 未结 4 1162
长发绾君心
长发绾君心 2021-02-05 06:21

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

When I tried to extend it by prototype

Math.prototype.randomBetwee         


        
4条回答
  •  名媛妹妹
    2021-02-05 06:46

    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.

提交回复
热议问题