Extend the number class

后端 未结 3 791
离开以前
离开以前 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:37

    You can extend natives JS objects by using (for example) Number.prototype.myFn = function(){}.

    So you could do :

    Math.prototype.odd = function(n){
        return n % 2 === 0;
    };
    
    Math.prototype.even = function(n){
        return n % 2 === 1;
    };
    

    And then use it like so :

    var two = 2;
    console.log(Math.odd(2)); // true
    

    BUT I would strongly advise you against extending natives in JavaScript. You can read more about it here

    EDIT : After trying my code on JSFiddle, it appears the Math object has no prototype, you can read more about it here. The code above won't work !

    Instead, you could do :

    Math.odd = function(n){
        return n % 2 === 0;
    };
    
    Math.even = function(n){
        return n % 2 === 1;
    };
    
    console.log(Math.odd(2)); // true
    

    or :

    Number.prototype.odd = function(){
        return this % 2 === 0;
    };
    
    Number.prototype.even = function(){
        return this % 2 === 1;
    };
    
    console.log(new Number(2).odd()); // true
    

提交回复
热议问题