【前端】Callback Function是什麼?
又稱為回呼函數、回調函數。
定義
當一個方法被當作參數傳入另一個方法,就稱作 Callback Function ←
·優點
- 有條件地執行方法,例如:點擊按鈕後才印出文字
- 控制方法的執行順序
- 減少宣告變數
·範例
1
//The item is a callback function
$(“#btn_1”).click(function() { }); alert(“Btn 1 Clicked”);
2
function greeting(name) {
ALOA
$(“#btn_1”).click(function() { alert(“Btn 1 Clicked”); });
2
function greeting(name) { alert(“Hello” + name); }
function processUserInput(callback ) {
var name = prompt(“輸入你的名字:”); callback(name);
processUserInput(greeting);
3.
function myDisplayer(some) { document.getElementById(“demo”).innerHTML = some;
function myCalculator (num1, num2, myCallback) { let sum = num1 + num2;
}
myCallback(sum);
myCalculator (5, 5, myDisplayer);
In the example above, myDisplayer is a called a callback function.
It is passed to myCalculator() as an argument.
Callback Hell (Callback 地獄)
參考資料
- 重新認識 JavaScript: Day 18 Callback Function 與IIFE-iT邦幫忙
- 回呼函式-術語表-MDN Web Docs
- Understand JavaScript Callback Functions and Use Them
- JavaScript Callbacks – W3Schools
- jQuery Callback Functions – W3Schools