【发布时间】:2017-05-13 07:09:29
【问题描述】:
我正在尝试捕获传递给回调“func”函数的参数。但是,当我尝试在“缓存”函数中控制日志参数时,除了回调函数的名称之外,它什么也不提供。
但是当我添加一个辅助内部函数时,日志记录工作得很好,它让我可以访问回调接收到的参数。我真的很想了解内部函数如何执行任务,但外部函数不能。
function cache(func) {
console.log(arguments); //logs { '0': [Function: complexFunction] }
return function () {
console.log(arguments); //logs { '0': 'foo', '1': 'bar' }
}
}
var complexFunction = function(arg1, arg2) { return arg1 + arg2 };
var cachedFunction = cache(complexFunction);
console.log(cachedFunction('foo', 'bar')); // complex function should be executed
【问题讨论】:
-
arguments指的是 current 函数的参数对象。因此,将其保存到另一个变量并使用它。 -
“内部函数如何执行任务,而外部函数不能” 这怎么可能?当您调用内部函数时,外部函数已经终止。
'foo'和'bar'被传递给 inner 函数。外部函数无法访问这些,因为它当时甚至没有运行。也许我误解了这个问题。
标签: javascript function callback arguments