我正在读一本书,包含了下面的例子:的JavaScript编写功能
var composition1 = function(f, g) {
return function(x) {
return f(g(x));
}
};
然后作者写道:” ......天真实施组成,因为它并不需要执行上下文考虑.. ”
所以优选功能是一个:
var composition2 = function(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
}
};
随后的整个例子:
var composition2 = function composition2(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
}
};
var addFour = function addFour(x) {
return x + 4;
};
var timesSeven = function timesSeven(x) {
return x * 7;
};
var addFourtimesSeven2 = composition2(timesSeven, addFour);
var result2 = addFourtimesSeven2(2);
console.log(result2);
难道有人请向我解释为什么组合函数是首选的(可能是一个例子)?
编辑:
在此期间我曾尝试使用方法作为参数的建议,但没有奏效。其结果是楠:如果你
var composition1 = function composition1(f, g) {
return function(x) {
return f(g(x));
};
};
var composition2 = function composition2(f, g) {
return function() {
return f.call(this, g.apply(this, arguments));
}
};
var addFour = {
myMethod: function addFour(x) {
return x + this.number;
},
number: 4
};
var timesSeven = {
myMethod: function timesSeven(x) {
return x * this.number;
},
number: 7
};
var addFourtimesSeven1 = composition1(timesSeven.myMethod, addFour.myMethod);
var result1 = addFourtimesSeven1(2);
console.log(result1);
var addFourtimesSeven2 = composition2(timesSeven.myMethod, addFour.myMethod);
var result2 = addFourtimesSeven2(2);
console.log(result2);
这实际上与咖喱无关。 – Bergi
你说得对,我改了措辞。 – JShinigami
它被称为功能组成!为什么你为了天堂而撰写方法?函数组合意味着以无咖啡因的方式将咖啡形式的纯函数组合在一起,而无副作用:'const compose = f => g => x => f(g(x))'。除了只有一个参数的curried函数(就像我们的'compose'函数)。函数组合仅适用于curried函数,因为函数只返回单个值。 – ftor