【发布时间】:2021-09-10 06:22:44
【问题描述】:
谁能给我解释一下这段代码
return pipe(...fns)(this);
我知道如果我们没有 (this),所以我们返回了缩减的函数,但 (this) 让我很困惑。
完整的源代码在这里。第 72 行 https://stackblitz.com/edit/typescript-hv4ntb
【问题讨论】:
标签: javascript functional-programming rxjs
谁能给我解释一下这段代码
return pipe(...fns)(this);
我知道如果我们没有 (this),所以我们返回了缩减的函数,但 (this) 让我很困惑。
完整的源代码在这里。第 72 行 https://stackblitz.com/edit/typescript-hv4ntb
【问题讨论】:
标签: javascript functional-programming rxjs
同理:
const pipeFunction = pipe(...fns); // pipe returns a function
const result = pipeFunction(this); // call the returned function with this as argument
return result; // return the result
因此,如果您看到类似 variable(...)(...) 的内容,您应该假设该变量的计算结果是一个返回函数的函数,可能像这样:
const variable = (a) => (b) => a + b;
variable(4)(2);
// ==> 6
const partial = variable(8)
[1, 2, 3].map(partial);
// ==> [9, 10, 11]
【讨论】:
据说Javascript有first-class functions(你可以在MDN上阅读更多内容),这意味着你可以用函数来做你可以用其他类型做的事情。将它们存储到变量中,将它们作为参数传递给其他函数,以及将它们用作其他函数的返回值。
想法是,只要将函数视为值。
在您的用例中,一个函数只是从另一个函数返回:
function multiply(times) {
return function(number) {
return number * times;
};
}
// as you can see, we are storing the "returned function"
// resulted from calling `multiply` into the `double` variable.
const double = multiply(2);
console.log(
double(5)
);
现在,当然,您可以将 double 变量短路,
然后直接调用返回的函数。
function multiply(times) {
return function(number) {
return number * times;
};
}
console.log(
multiply(2)(5)
);
【讨论】: