I try to extend JavaScript Math. But one thing surprised me.
When I tried to extend it by prototype
Math.prototype.randomBetwee
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
Math object is the prototype of the new MyMath objectMyMath has access to all functionality of MathMyMath without manipulating Maththis to refer to the Math functionalityThere 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.