Functions
函式是主要建構專案的材料,不用複寫就可以可以重複使用。
Function Declaration
只要寫一次就可以重複使用,修改只需修改函式
function showMessage() {
alert( 'Hello everyone!' );
}
showMessage();
showMessage();Local variables
在函式內宣告的變數只能在函式內使用。
function showMessage() {
let message = "Hello, I'm JavaScript!"; // local variable
alert( message );
}
showMessage(); // Hello, I'm JavaScript!
alert( message ); // <-- Error! The variable is local to the functionOuter variables
Parameters
Default values
若未帶入參數,值會變成 undefined,可以用 = 指定預設值,舊版的 JavaScript 不支持預設值。
Returning a value
return 可以使用在函式的任何位置,一旦返回值,函式停止執行。
函示沒有返回值或返回空的值,會返回 undefined。
return 不能換行,換行會返回 undefined。
Naming a function
函式是動作,名子通常是動詞,簡短正確的描述該函式要做的動作;團隊決定前綴動詞的意思;函式只做一件事,不同的功能要拆分成不同函式。
show 代表顯示東西
get 返回值
calc 計算值
create 創造東西
check 返回布林值
Functions == Comments
函式要簡短只做一個功能,如果功能太複雜,要拆成幾個小函式再組合起來。
Last updated
Was this helpful?