Implement (5) .add (3) .minus (2) function

Realize (5) .add (3) .minus (2) Function: 5 + 3-2 = 6

method one

    Number.prototype.add = function (number) {
      if (typeof number !== 'number') {
        throw new Error('请输入数字~');
      }
      return this.valueOf() + number;
    };
    Number.prototype.minus = function (number) {
      if (typeof number !== 'number') {
        throw new Error('请输入数字~');
      }
      return this.valueOf() - number;
    };
    console.log((5).add(3).minus(2));

Method two: here ~ can be written as plus sign + minus sign-it works. But must be a unary expression

 // Add ~ unary operator in front of anonymous function will be transformed into function expression, add (), 
    ~ function () {
         function add (n) {
           return  this + n 
        } 
        function minus (n) {
           return  this - n- 
        } 
        Number.prototype.add = the Add 
        Number.prototype.minus = minus 
    } () 
    the console.log (( . 5) .add (. 3) .minus (2))

Method 3: Do not use the anonymous function and unary expression in method two; the most common method

    function addmin(){
        function add(n){
          return this+n
        }
        function minus(n){
          return this-n
        }
        Number.prototype.add = add
        Number.prototype.minus = minus
    }
    addmin()
    console.log((5).add(3).minus(2))

 

Guess you like

Origin www.cnblogs.com/yaya-003/p/12691314.html