᳓相關文章
᳓重點整理
- Callback function能夠將原本塞在同一個function中的程式碼再度細分成獨立的function。在下面的例子中,使用Callback function的寫法不需要在function calc中寫許多的if也能夠達到相同的執行結果。
- 若Callback function在程式中只使用一次,可以不為function命名,因此被稱為Anonymous function。
᳓實作
一般function的寫法:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Basic function | |
* 功能:建立一個可以回傳num1+num2、num1*num2的function | |
* | |
*/ | |
let calc = function(num1, num2, calcType){ | |
if(calcType == "add"){ | |
return num1 + num2; | |
} | |
else if(calcType == "multiply"){ | |
return num1 * num2; | |
} | |
}; | |
console.log("2 + 3 = " + calc(2, 3, "add")); | |
console.log("2 * 3 = " + calc(2, 3, "multiply")); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Basic function using callback function | |
* 功能:建立一個使用了callback function回傳num1+num2、num1*num2的function | |
* | |
*/ | |
let add = function(num1, num2){ | |
return num1 + num2; | |
} | |
let multiply = function(num1, num2){ | |
return num1 * num2; | |
} | |
let calc = function(num1, num2, callback){ | |
return callback(num1, num2); | |
} | |
console.log("2 + 3 = " + calc(2, 3, add)); | |
console.log("2 * 3 = " + calc(2, 3, multiply)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* | |
* Basic function using anonymous function | |
* 功能:建立一個使用了anonymous function回傳num1-num2的function | |
* | |
*/ | |
let calc = function(num1, num2, callback){ | |
return callback(num1, num2); | |
} | |
console.log("2 - 3 = " + calc(2, 3, function(num1, num2){ | |
return num1 - num2 | |
})); |
執行結果 |