我是通过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()'的功能;第二种方法需要一个“全局”变量。 –