【问题标题】:Could anyone explain how the below code block works?谁能解释下面的代码块是如何工作的?
【发布时间】:2018-12-30 06:38:57
【问题描述】:

将猫传递给 func 如何返回回调?

let animal = '';
const fetchAnimal = func => {
  func('cats');
};

fetchAnimal(name => {
  //logs cats to the console
  console.log(name);
});

【问题讨论】:

  • callback function meaning的可能重复
  • 见tag wiki。
  • 能否请您澄清一下您对此代码的不理解之处?还有你所说的“如何将猫传递给 func 返回回调”是什么意思 - 即你认为返回回调的确切内容是什么?
  • 更好——只需使用fetchAnimal(console.log)调用它
  • 谢谢。我现在可以理解上下文了。

标签: javascript ecmascript-6 callback arrow-functions


【解决方案1】:

这里我们将一个函数作为参数传递给函数调用中的fetchAnimal,该函数调用映射到func 变量。因此,当您调用 func('cats') 时,它最终会调用您在函数调用期间传递的函数,其中 cats 作为映射到变量 name 的参数。

const fetchAnimal = func => {
  func('cats');
};

fetchAnimal(name => {
  console.log(name);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2018-12-24
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多