javascript - 跟踪高阶函数中的变量

标签 javascript higher-order-functions

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

// 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,并且由于它们在其存在的同一作用域中仍然具有可能的引用,因此它不会被销毁,从而可以在作用域内使用。

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

关于javascript - 跟踪高阶函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55463642/

相关文章:

c++ - 处理函数对象

haskell - Haskell 函数是高阶的当且仅当它的类型有多个箭头?

javascript - React Ajax 请求给出 CORS 错误但返回数据

javascript - 如何刷新单个div的内容

javascript - 异步 js 验证表单

javascript - 从树中消除根元素,如表示数据

javascript - jquery 速度不够快,无法生效

Javascript .load 看不到 PHP 的变量

scala - Scala 函数是否可以编写为获取任何函数并以相反的参数返回该函数?

sml - 什么是 ML 中高阶函数中的 curry 和 uncurry