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