Extending Math object through prototype doesn't work

前端 未结 4 1115
长发绾君心
长发绾君心 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:53

    To quote this answer:

    Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by Func.prototype.

    The reason you can't assign to its prototype using .prototype is because the Math object has already been created.

    Fortunately for us, we can assign new properties to the Math object by simply using:

    Math.myFunc = function() { return true };
    

    In your case, this would be:

    Math.randomBetween = function(...) { ... };
    

提交回复
热议问题