gpt4 book ai didi

javascript - 传递函数表达式变量作为​​参数有什么用?

转载 作者:行者123 更新时间:2023-11-29 19:38:33 24 4
gpt4 key购买 nike

我是一名初级 JS 程序员,正在学习 codeschool 的第 3 门 JS 类(class)。他们的一个模块引入了将函数表达式变量作为​​参数传递给其他函数的概念。但是,我需要一些帮助来理解为什么这种方法在某些情况下比在其他情况下更好。例如,以下代码用于条件警报,该警报应该识别用户是否是新用户并在用户注销系统时抛出自定义问候语。

这是 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 并返回所需的问候语?

最佳答案

在您的情况下,它并不是天生就更好。

但有些情况并非如此简单。假设你不能修改 closeTerminal 函数,但它的开发者仍然希望你从他的逻辑深处执行任意功能?那就是你使用 callback function 的地方.为它们传递函数表达式是很自然的,但并不是严格要求的。看看purpose of callbacks in javascript也许吧。

回调的另一个用例是异步函数,您稍后可能会遇到它们。

一个更好的例子可能是

function closeTerminal(getMessage) {
var isNewCustomer = !Math.round(Math.random()); // complicated, local logic

var message = getMessage(isNewCustomer);
alert(message); // print to the closing terminal
// (which is local to this function as well)
}

你可以调用它

closeTerminal(function greeting(newCustomer) {
// passing a custom function to determine the appropriate message
if (newCustomer)
return "Thanks for visiting the Badlands!\nWe hope your stay is...better than most.";
else
return "Welcome back to the Badlands!\nGuess they aren't so bad huh?";
});

关于javascript - 传递函数表达式变量作为​​参数有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24319557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com