[英]How to add a function to Function.prototype in JavaScript?
我正在嘗試JavaScript中的一些基本FP技術。 compose
函數接受兩個函數並給出其Composition函數。 現在,我想組成Function
的一部分,以便可以輕松地鏈接它。
var compose = (func1, func2) => (args => func2(func1(args)));
var square = x => x * x;
var cube = x => x * x * x;
var sixthPower = compose(cube, square);
console.log(sixthPower(2)); // 64
console.log(compose(cube, x => x)(3)); // 27
Function.prototype.compose = function(func) {
return function(args) {
func(/* not sure what to write here */)
}
}
// to make this possible
console.log(square.compose(cube)(3));
您需要存儲原始的this
引用,因此可以在返回的函數中使用它:
var square = x => x * x; var cube = x => x * x * x; Function.prototype.compose = function(func) { var self = this; return function(args) { return func(self(args)) } } console.log(square.compose(cube)(3));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.