尝试学习功能混合

时间:2018-08-31 10:21:19

标签: javascript prototype

我有计算器功能:

var Calculator = function(a, b) { 
  this.add = function(a, b) { return a + b; }; 
  this.multiply = function(a, b) { return b * a; }; 
  this.subtract = function(a, b) { return a - b; }; 
  this.divide = function(a, b) { 
    if (a/b === Infinity) {
      return Infinity - Infinity; 
    } else return a/b; 
  }; 
};

我想为'sum'(Calculator.sum)创建一个功能混合,因此如果我将“ 1、2、3、4”传递给它,它将返回10,但不是计算器的属性

有人可以解释如何做到吗?

2 个答案:

答案 0 :(得分:1)

假设您正在谈论here中所述的功能混合模式:

const withSum = (object) => {
  return Object.assign({}, object, {
    sum(...args) {
      return args.reduce((sum, number) => sum + number, 0);
    }
  });
};

var Calculator = function(a, b) { 
  this.add = function(a, b) { return a + b; }; 
  this.multiply = function(a, b) { return b * a; }; 
  this.subtract = function(a, b) { return a - b; }; 
  this.divide = function(a, b) { 
    if (a/b === Infinity) {
      return Infinity - Infinity; 
    } else return a/b; 
  }; 
};

var calculator = withSum(new Calculator(1, 2));

console.log('calculator.add(1, 2):', calculator.add(1, 2));
console.log('calculator.multiply(1, 2):', calculator.multiply(1, 2));
console.log('calculator.subtract(2, 1):', calculator.subtract(2, 1));
console.log('calculator.divide(1, 2):', calculator.divide(1, 2));
console.log('calculator.sum(1, 2, 3, 4): ', calculator.sum(1, 2, 3, 4));

请注意,如果您的Calculator.divide应该返回NaN,如果a/b === Infinity您可以简单地写return NaN;而不是Infinity - InfinityNaN是全局常量)。

此外,您可以删除在Calculator构造函数中声明的形式参数列表:function Calculator() {...}就足够了,因为您从不使用a, b

答案 1 :(得分:0)

您可以使用以下代码:

Calculator = ..;                         // maybe [], {} or function() {...}
Calculator.sum = function(){
   var result = 0;
   for (var i = 0; i<arguments.length; i++)
       result+= arguments[i];
   return result;
};

如果将1,2,3,4个参数传递给Calculator.sum,它将返回10。

Calculator.sum(1, 2, 3, 4); // 10

Chrome DevTools屏幕截图

Chrome DevTools Screenshot

相关问题