跟踪高阶函数中的变量

赛义德·奥斯塔德

任何人都可以解释一下在运行完函数后变量值如何存在吗?我看到了高阶函数的代码示例,但我不明白它如何在每次运行函数后跟踪函数中的变量。在下面的示例中,变量计数如何在每次运行后添加更多?

// Higher order functions

// A higher order function is any function that does at least one of the following
//   1. Accepts a function as an argument
//   2. Returns a new function

// Receives a function as an argument
const withCount = fn => {
  let count = 0

  // Returns a new function
  return (...args) => {
    console.log(`Call counts: ${++count}`)
    return fn(...args)
  }
}

const add = (x, y) => x + y

const countedAdd = withCount(add)

console.log(countedAdd(1, 2))
console.log(countedAdd(2, 2))
console.log(countedAdd(3, 2))

弗朗西斯科

注意 withCount 函数只调用一次:

const countedAdd = withCount(add)

在该调用之后,该变量count被创建,并且因为它们在存在的同一范围内仍然有可能的引用,所以它不会被销毁,从而可以在范围内使用。

请注意,返回的箭头函数在作用域内(函数 withCount)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章