【问题标题】:How to access callback arguments within another function?如何访问另一个函数中的回调参数?
【发布时间】: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


【解决方案1】:

内部函数是一个不同的函数。当您调用它时(因为它已被返回并分配给cachedFunction),您向它传递不同的参数。

cachedFunction('foo', 'bar')

应该执行复杂的功能

不是。

你永远不会执行complexFunction

您将它作为参数传递给cachecache 将它(写入arguments 对象)传递给console.log,但它永远被调用。

如果你想调用它,那么你需要实际这样做。

function cache(func) {
  console.log(arguments); //logs { '0': [Function: complexFunction] }

  return function () {
  console.log(func.apply(null, arguments));
  }
}

【讨论】:

  • 谢谢!抱歉,我忘了删除关于执行的评论。我对内部函数从哪里获取参数非常感兴趣。我特别喜欢你在这里写的:“内部函数是一个不同的函数。当你调用它时(因为它已被返回并分配给 cachedFunction),你传递给它不同的参数。”能否请您详细说明一下?
  • @dsvorc41:您在此处调用内部函数:cachedFunction('foo', 'bar')。因此它得到参数'foo''bar'
  • @dsvorc41 — 在我说“你传递不同的参数”之后,我引用了将参数传递给内部函数的那段代码
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
相关资源
最近更新 更多