我是通過codechool的第3個JS課程開始工作的一名JS程序員。其中一個模塊引入了傳遞函數表達式變量作爲其他函數參數的概念。但是,我需要一些幫助來理解爲什麼在某些情況下這種方法比其他方法更好。例如,以下代碼適用於條件警報,用於識別用戶是否是新用戶,並在用戶註銷系統時拋出自定義問候語。傳遞函數表達式變量作爲參數的用途是什麼?
這是codeschool倡導者:
var greeting;
var newCustomer;
//Some code sets the variable newCustomer to true or false
if(newCustomer){
greeting = function() {
alert("Thanks for visiting the Badlands!\n" +
"We hope your stay is...better than most.");
};
} else {
greeting = function() {
alert("Welcome back to the Badlands!\n" +
"Guess they aren't so bad huh?");
};
}
closeTerminal(greeting);
function closeTerminal(message){ message();}
但是,爲什麼是比下面的更好嗎?
var greeting;
var newCustomer;
//Some code sets the variable newCustomer to true or false
closeTerminal();
function closeTerminal(){
if(newCustomer) {
alert("Thanks for visiting the Badlands!\n" +
"We hope your stay is...better than most.");
} else {
alert("Welcome back to the Badlands!\n" +
"Guess they aren't so bad huh?");
}
}
哪個代碼塊(或任何其他代碼)是一個好的開發人員用來實現所需的結果?通過使用單個if . . . else
語句評估newCustomer並返回所需的問候語,將整個函數存儲在變量中是否有優勢?
調用它的第一個保持'newCustomer'本地調用'closeTerminal()'的功能;第二種方法需要一個「全局」變量。 –