ใน JavaScript เนื่องจากฟังก์ชั่นเป็นวัตถุดังนั้นเราจึงสามารถส่งผ่านเป็นพารามิเตอร์ไปยังฟังก์ชั่นอื่นได้ ฟังก์ชันเหล่านี้สามารถเรียกใช้ภายในฟังก์ชันอื่นได้ และฟังก์ชันที่ส่งผ่านจะเรียกว่าฟังก์ชันเรียกกลับ
ต่อไปนี้เป็นรหัสสำหรับการเรียกกลับ JavaScript -
ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
</style>
</head>
<body>
<h1>JavaScript Boolean constructor Property</h1>
<p class="sample"></p>
<button class="btn">CLICK HERE</button>
<h3>
Click on the above button to call the add function which calls back
another function
</h3>
<script>
function add(a, b, callback) {
callback(a + b);
}
function multiplyResultByTwo(res) {
document.querySelector(".sample").innerHTML = res * 2;
}
document.querySelector(".btn").addEventListener("click", () => {
add(4, 5, multiplyResultByTwo);
});
</script>
</body>
</html> ผลลัพธ์

เมื่อคลิกปุ่ม “คลิกที่นี่” -
