Extend the number class

后端 未结 3 820
离开以前
离开以前 2021-01-24 10:12

I want to extend the number class to have instance functions such as odd and even so I can do something like this:

2.odd() => false
         


        
3条回答
  •  日久生厌
    2021-01-24 10:42

    I think as long as you understand the side-effects of your "extension" then you're okay. I often modify the String prototype to add an "elipsis" method so I can do things like

    "SomeString".elipsis()
    

    But start at the beginning. You're not "extending classes" in JavaScript. JavaScript is a prototype-based language. You can modify prototypes to do what you need.

    You won't be able to add a method directly to the number itself. You can, however modify the prototype of the Number object:

    Number.prototype.even = function(){    
        return this.valueOf() % 2 === 0;
    }
    

    With this, you won't be able to use the following syntax:

    10.even();
    

    But, since you aren't hard-coding stuff, otherwise you wouldn't need this function anyways, you CAN do the following:

    var a = 10;
    a.even(); //true
    

    I might say that you could consider adding a utilities object to do these things, because modifying primitive prototypes is not always guaranteed to be side-effect free.

    This function does not really provide any gain for you. You're checking for odd and even, replacing one line of code with another. Think about the difference:

    var a = 10;
    var aIsEven = a.even();
    

    vs:

    var a = 10;
    var aIsEven = a % 2 === 0;
    

    You gain three characters of code, and the second option is less likely to break your "JavaScript".

提交回复
热议问题