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

后端 未结 2 1514
北荒
北荒 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:23

    Yes, you can easily inherit from the Number.prototype. The trick is to make your objects convertible to numbers by giving them a .valueOf method:

    function NumLib(n) {
        if (!(this instanceof NumLib)) return new NumLib(n);
        this.valueOf = function() {
            return n;
        }
    }
    NumLib.prototype = Object.create(Number.prototype);
    NumLib.prototype.square = function () { return this * this }
    

    The cast will happen whenever a mathematical operation is applied to the object, see also this answer. The native Number methods don't really like to be called on derived objects, though.

提交回复
热议问题