【问题标题】:Are closures higher order functions?闭包是高阶函数吗?
【发布时间】:2018-12-22 22:41:45
【问题描述】:

高阶函数定义为:

将函数作为参数和/或将函数作为返回值返回的函数。

闭包示例:

function outer() {
  const name = 'bob';

  function inner(lastName) {
    console.log('bob' + lastName);
  }

  return inner;
}

上面定义的闭包是否属于这一类?好像他们返回一个函数作为返回值,对吧?

【问题讨论】:

  • 这是一个返回函数的函数,所以确定。
  • 返回另一个函数的函数是否是高阶函数值得怀疑。采用函数参数是使函数更高阶的原因。

标签: javascript closures


【解决方案1】:

闭包确实意味着它必须由函数返回。在 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();

【讨论】:

    【解决方案2】:

    是的,闭包是高阶函数。它们是返回函数的函数。

    【讨论】:

      【解决方案3】:

      闭包允许从内部函数访问外部函数的作用域。闭包通常用于为对象提供数据隐私。

      高阶函数是接收函数作为参数或返回函数作为输出的函数。

      //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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-07
        相关资源
        最近更新 更多