JavaScript 如何创建自定义回调函数
回调函数是在函数执行完后被调用的函数。由于JavaScript是一种事件驱动的语言,在移动到下一个函数之前,它不会等待函数执行完。通过回调函数,可以在另一个函数执行完后再执行该函数。
JavaScript中的所有函数都是对象,因此像其他对象一样,JavaScript函数可以将另一个函数作为参数传递。有许多内置函数使用回调函数。
可以使用callback关键字作为最后一个参数来创建自定义回调函数。然后可以在函数末尾调用callback()函数来调用它。变量typeof是可选使用的,用于检查传递的参数是否是函数。
语法:
function processThis(message, callback) {
console.log("Running function first with message: " + message);
if (typeof callback == "function")
callback();
}
processThis("Hello World", function callFunction() {
console.log("This is a callback function.")
});
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to create a custom
callback in JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to create a custom
callback in JavaScript?
</b>
<p>
See the console for
output of the functions
</p>
<script type="text/javascript">
function processThis(message, callback) {
console.log(
"Running function first with message: "
+ message);
if (typeof callback == "function")
callback();
}
processThis("Hello World", function callbackFunction() {
console.log("This is a callback function.")
});
</script>
</body>
</html>
输出:
非匿名回调函数:
回调函数并不总是需要定义为匿名函数。它可以在其他地方定义,并且以后可以将此函数用作回调。在传递回调函数时不使用括号。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to create a custom
callback in JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>How to create a custom
callback in JavaScript? </b>
<p>See the console for output
of the functions</p>
<script type="text/javascript">
function processThis(message, callback) {
console.log("Running function first
with message: " + message);
if (typeof callback == "function")
callback();
}
function callbackFunction() {
console.log(
"Running callback function next");
}
processThis("Hello World", callbackFunction);
</script>
</body>
</html>
输出:
回调函数中的参数:
调用函数在自己的主体中调用回调函数时,回调函数也可以有自己的参数,并且可以传递值。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to create a custom
callback in JavaScript?
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>How to create a custom callback
in JavaScript?</b>
<p>See the console for output of the functions</p>
<script type="text/javascript">
function processThis(message, callback) {
console.log(
"Running function first with message: "
+ message);
if (typeof callback == "function")
callback(9, "Hello!");
}
function callbackFunction(num, str) {
console.log("Running callback function next");
console.log("num value is: " + num);
console.log("str value is: " + str);
}
processThis("Hello World", callbackFunction);
</script>
</body>
</html>
输出: