什么时候应该将函数存储到变量中? [英] When should I store a function into a variable?

查看:39
本文介绍了什么时候应该将函数存储到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻我正在学习JavaScript,但我不太了解何时将函数写入变量.

I'm learning JavaScript at the moment and I don't quite understand when to write a function into a variable.

例如,以下两个代码块在Node.js中执行完全相同的操作:

For instance, both of the following code blocks do the exact same thing in Node.js:

 var onReq = function(req, res) {
   res.write('Hello');
 };

 http.createServer(onReq).listen(3000);

function onReq(req, res) {
   res.write('Hello');
 }

 http.createServer(onReq).listen(3000);



哪种方法是最佳实践中的最佳选择,为什么?



Which is the best method to do according to best practices, and why?

推荐答案

通常,当我需要重新定义操作时,通常只使用 var funcName = function(){} 稍后再进行该功能.例如:

Usually I'll only use a var funcName = function(){} when I would need to redefine the action(s) for that function later on. For example:

var foo = function(a){ return a * 2; }
var bar = foo(2);

foo = function(a){ return a / 2; }

bar = foo(bar);

否则,对于大多数目的(假设它不是回调或修饰符),通常可以经典地"声明函数.

Otherwise, for most purposes (assuming it's not a callback or a modifier) declaring a function "classically" is usually acceptable.

这篇关于什么时候应该将函数存储到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆