Extending Math object through prototype doesn't work

前端 未结 4 1158
长发绾君心
长发绾君心 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 07:09

    var MyMath = Object.create(Math); // empty object with prototype Math
    
    MyMath.randomBetween = function (a, b) {
        return this.floor(this.random() * (b - a + 1) + a);
    };
    
    typeof(MyMath);                 // object
    Object.getPrototypeOf(MyMath);  // Math
    MyMath.PI;                      // 3.14...
    MyMath.randomBetween(0, 10);    // exactly that
    
    • the Math object is the prototype of the new MyMath object
    • MyMath has access to all functionality of Math
    • you can add your custom functionality to MyMath without manipulating Math
    • within your custom methods, use keyword this to refer to the Math functionality

    There is no Monkey Patching with this approach. This is the best way to extend JavScript Math. There is no need to repeat the explanations from the other answers.

提交回复
热议问题