![](/img/trans.png)
[英]How can I create 1 or 2 higher order functions / closures as a alternative to a class with methods?
[英]Are closures higher order functions?
高阶函数定义为:
将函数作为参数和/或返回函数作为返回值的函数。
闭包示例:
function outer() {
const name = 'bob';
function inner(lastName) {
console.log('bob' + lastName);
}
return inner;
}
像上面定义的那样的闭包是否属于这一类? 看起来他们返回一个函数作为返回值,对吧?
闭包并不意味着它必须由函数返回。 在 JavaScript 中,每个函数实际上都是一个闭包。 闭包通常是一个可以访问声明上下文范围的函数。
function outer(lastName) { const name = 'Bob'; function inner(lastName) { // here we have access to the outer function's scope // thus it IS a closure regardless whether we return the function or not console.log(name + ' ' + lastName); } inner(lastName); } outer('Marley');
更具体地说:闭包实际上是将当前范围绑定到子上下文的概念。 我们经常对获得此类映射上下文的函数说“闭包”。 声明上下文并不意味着声明时间,更多的是在调用时处于活动状态的声明上下文。 此行为用于将上下文绑定到内部函数并返回具有绑定上下文的函数:
function outer(lastName) { // this is the declaration context of inner(). const name = 'Bob'; function inner() { // here we have access to the outer function's scope at its CALL time (of outer) // this includes the constand as well as the argument console.log(name + ' ' + lastName); } return inner; } var inner1 = outer('Marley'); var inner2 = outer('Miller'); function output() { // this is the caller context, the const name ist NOT used const name = 'Antony'; inner1(); // outputs 'Bob Marley' inner2(); // outputs 'Bob Miller' } // test the output output();
闭包允许从内部函数访问外部函数的作用域。 闭包通常用于为对象提供数据隐私。
高阶函数是接收函数作为参数或返回函数作为输出的函数。
//This function is a higher order function
function higherOrderFunction(f, ...outerArgs) {
return function (...innerArgs) {
// It has access to outer args. So we can say this function has a closure over the scope of outer function
let args = [...outerArgs, ...innerArgs];
return f.apply(this, args);
};
}
const f = function (x, y, z) { return x * y * z };
higherOrderFunction(f, 1)(1, 3) // => (1*2*3);
是的,闭包是高阶函数。 它们是返回函数的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.