From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- files/zh-cn/glossary/callback_function/index.html | 36 +++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 files/zh-cn/glossary/callback_function/index.html (limited to 'files/zh-cn/glossary/callback_function') diff --git a/files/zh-cn/glossary/callback_function/index.html b/files/zh-cn/glossary/callback_function/index.html new file mode 100644 index 0000000000..b5efc095d8 --- /dev/null +++ b/files/zh-cn/glossary/callback_function/index.html @@ -0,0 +1,36 @@ +--- +title: 回调函数 +slug: Glossary/Callback_function +tags: + - Callback + - 回调函数 +translation_of: Glossary/Callback_function +--- +

被作为实参传入另一函数,并在该外部函数内被调用,用以来完成某些任务的函数,称为回调函数。

+ +

例如:

+ +
function greeting(name) {
+  alert('Hello ' + name);
+}
+
+function processUserInput(callback) {
+  var name = prompt('请输入你的名字。');
+  callback(name);
+}
+
+processUserInput(greeting);
+ +

以上范例为 {{glossary("synchronous","同步")}} 回调,它是立即执行的。

+ +

然而需要注意的是,回调函数经常被用于继续执行一个{{glossary("asynchronous","异步")}} 完成后的操作,它们被称为异步回调。例如,这个简单 的 maps-example.html 例子(live 链接点此)使用了 Google Maps 以及 Geolocation 的 API 来展示您设备的当前位置。

+ +

由于从 GPS 得到设备坐标信息的操作为异步的(我们不知道何时数据会被返回),所以 {{domxref("Geolocation.getCurrentPosition()")}} 方法接收一个匿名回调函数作为形参,而该回调函数则接收传回的坐标数据作为形参。该函数只在坐标数据返回后才执行。

+ +

了解更多

+ +

基础知识

+ + -- cgit v1.2.3-54-g00ecf