[Day21] 回呼函式 Callback Function

先来看看 MDN 的定义。

回呼函式(callback function)是指能藉由 argument 通往另一个函式的函式。它会在外部函式内调用、以完成某些事情。

所以我想像的是:

const foo1 = function(){...};
const foo2 = function(){...};

foo2(foo1);

根据 008 所叙述,其实 callback function 跟一般函式没什麽不同,差别在於被呼叫执行的时机;JavaScript 是一个事件驱动(Event-driven)的程序语言,而事件驱动的概念是:
事件被触发(Event fired)->处理事件(Event handler)

拿生活上的事件来举例:
门铃响->开门,一般来说我们会依照事件的执行顺序来写程序码,所以会先写 action1 门铃响,然後再接着 action2 开门:

function action1() {
  console.log("Doorbell ringing");
}

function action2() {
  console.log("Open the door");
}

action1();
action2();

// Doorbell ringing
// Open the door

如上例所说,若想让事件先发生(也就是 action1),就会把程序码写在前面,如果是透过 callback function 来改写,会把函式当作参数传进另一个函式:

function action1(callback) {
  console.log("Doorbell ringing");
  callback();
}
function action2() {
  console.log("Open the door");
}
action1(action2);
// Doorbell ringing
// Open the door

为什麽要学 callback function? 因为在 array.methods 的参数会使用到 callback function,例如:array.prototype.maparray.prototype.filter 以後有遇到再说,先酱~

参考资料

008天重新认识JavaScript
回呼函式-MDN


<<:  【Day 21】Google Apps Script - API Blueprint 篇 - API Blueprint 介绍

>>:  Day22 Vue 认识Porps(1)

[Day 13 - Git] Git版本控管,没有它救不回来的专案

为什麽要做版本控管? 其实版本控管就是备份的概念,相信大家都有体会过档案误删、当机资料消失的经验,养...

Day 1: 所以到底什麽是Nativescript

Nativescript简介 Nativescript是一个用来写跨平台app的框架,一套code可...

[DAY 22] _SPI协议(2)

昨天介绍到spi基本协议的样子,今天在讲讲四种模式的差别,个别有两个模式名层: 1.CPOL(clo...

如何使用 Github Actions 自动部署 Angular 到 Github Pages

Github 多了一个 Actions 的新功能,当 push 档案到 Github 的时後,就会自...

4.1 Design System 尾声

这段时间看了各个设计系统其实也学了不少 之後或许就是自己试着从每个专案中慢慢建立起一套看看 今天想要...