In JavaScript, is there a way to inherit from the Number function?

后端 未结 2 1532
北荒
北荒 2021-01-25 17:34

So I know I can do this...

Number.prototype.square = function () { return this * this }
 [Function]
4..square()
 16

Is there a way to inherit f

2条回答
  •  情深已故
    2021-01-25 18:13

    using Object.defineProperty allows you to have a little more control over the object.

    Object.defineProperty(Number.prototype,'square',{value:function(){
     return this*this
    },writable:false,enumerable:false});
    //(5).square();
    

    with your own lib it's the same...

    Object.defineProperty(NumLib.prototype,'square',{value:function(){
     return this.whatever*this.whatever
    },writable:false,enumerable:false});
    

提交回复
热议问题