# 章序号/节序号/节/笔记序号 codecademy, Iterators, High-Order Function # 概念阐释 - 回调函数a是作为另一个函数b的**参数**传递给该函数b,并在该函数b内部被调用的函数a。简而言之,它是在另一个函数内部被定义和使用的函数。 - 处理[[JavaScript 异步1|异步]]事件 - 别和调用函数混淆,calling function ![](http://image.harryrou.wiki/2023-03-01-%E6%88%AA%E5%B1%8F2023-03-02%2007.13.03.png) - 定义了2个函数`greeting`和`sayGoodbye` - `greeting`函数中有2个参数,`name`字符串和`callback` **函数**占位符 - `greeting`函数要执行的语句为`print `和调用函数`callback();` - `sayGoodbye`是`greeting`要调用的函数,在最后的结果中会执行`sayGoodbye`函数中的语句 - 当调用函数`greeting('Alice',sayGoodbye);` 时结果为:`Hello,Alice!Goodbye!` # 举例子 ![](http://image.harryrou.wiki/2023-03-02-%E6%88%AA%E5%B1%8F2023-03-02%2011.39.21.png) ```js const higherOrderFunc = param => {   //调用函数语句 param();   // return a function :param函数作为higherOrderFunc的参数,param();相当于param作为调用函数被唤醒了。 return `I just invoked ${param.name} as a callback function!`} const anotherFunc = () => {  return 'I\'m being invoked by the higher-order function!';} //anotherFunc函数作为参数被高阶函数调用 higherOrderFunc(anotherFunc); //print:I just invoked anotherFunc as a callback function! ``` - 定义了2个函数`higherOrderFunc`和`anotherFunc` - `greeting`函数中有1个参数,`param`是 **函数**占位符 - `greeting`函数要执行的语句为调用函数`param();` 和 return 一段话 - `anotherFunc`是`higherOrderFunc`要调用的函数,在最后的结果中会执行`anotherFunc`的语句param(); = anotherFunc() - 当调用函数`higherOrderFunc(anotherFunc);` 时结果为: # 类比、比较与对比 在这个例子中,我们用一个计数为 10 的匿名函数`i`(一个没有名字的函数)调用了 higherOrderFunc()。匿名函数也可以是参数! ![](http://image.harryrou.wiki/2023-03-02-%E6%88%AA%E5%B1%8F2023-03-02%2011.48.04.png) # 问题 1. 写一个回调函数 - 高阶函数为printMsg, evenFunc,num - 函数为isEven, return n % 2 == 0; - 高阶函数的语句为:设定回调函数为变量*便于在字符串中添加*,console.log(`The number ${num} is an even number: ${isNumEven}.`) - 调用高阶函数 1. 函数为无参数的回调函数 - 函数为`anotherFunc`, 返回`'I\'m being invoked by the higher-order function!';` - 高阶函数为`higherOrderFunc`, 返回 `I just invoked ${显示低阶函数名字} as a callback function!` ` # 问题答案 有参数的回调函数:被使用的函数和参数都要写清楚。另一种写法见[[js function Helper Functions]] ```js let isEven = (n) => { return n%2 === 0; }; let printMsg = (func,num) => { return `The number ${num} is an even number: ${func(num)}`; }; console.log(printMsg(isEven,6)); ``` 函数为无参数的回调函数: ```js const higherOrderFunc = param => {   param();  //可写可不写 return `I just invoked ${param.name} as a callback function!` }; const anotherFunc = () => {   return 'I\'m being invoked by the higher-order function!'; }; console.log(higherOrderFunc(anotherFunc)); //print:I just invoked anotherFunc as a callback function! ``` # 备注(经验集/错误集) ## 经验集 - *回调函数不用写return,其它还是要写,不然不能打印结果* - *回调函数中的低阶函数必须是有参数的* ## 错误集 ## 参考资料 - [回调函数](https://developer.mozilla.org/zh-CN/docs/Glossary/Callback_function) - [[JavaScript 异步1|异步]] 回调函数的主要作用是在**异步编程**中处理异步事件和操作的结果。当我们在发起**异步操作**(**如网络请求或读取文件**)时,我们无法确定**何时可以得到操作结果**,因此我们需要传递一个回调函数给该异步操作,并在异步操作完成后调用该回调函数来处理操作结果。回调函数在异步编程中被广泛使用,例如在JavaScript中的事件处理、定时器、Promise、async/await等中。