我有一个计算器功能:
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)创建一个函数mixin,所以如果我将“ 1,2,3,4”传递给它,它将返回10,但不是Calculator的属性
有人可以解释如何做到吗?
最佳答案
假设您正在谈论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
。关于javascript - 尝试学习功能混合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52113375/