我有计算器功能:
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,但不是计算器的属性
有人可以解释如何做到吗?
答案 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 - Infinity
(NaN
是全局常量)。
此外,您可以删除在Calculator
构造函数中声明的形式参数列表:function Calculator() {...}
就足够了,因为您从不使用a, b
。
答案 1 :(得分:0)