为什么使用匿名函数? [英] Why are anonymous functions used?

查看:23
本文介绍了为什么使用匿名函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
使用有什么好处匿名函数而不是 JavaScript 事件代码中回调和参数的命名函数?

我一直在阅读/编写一些基本的 Javascript 和 JQuery 代码,并注意到在我阅读的几乎每个教程中,都使用匿名函数而不是命名函数.

I've been reading/writing some basic Javascript and JQuery code and noticed that in almost every tutorial that I read, anonymous functions are used instead of named functions.

例如,类似于:

$('document').ready(function(){
    alert("I am ready.");
});

对比:

function ready(){
    alert("I am ready.");
}

$('document').ready(ready());

第二个例子不是更容易阅读/理解吗?现在,我意识到这些都是非常简单的例子,但我想说明的是,我觉得匿名函数使代码看起来混乱且难以理解.到处都有大括号和括号,您不能在其他任何地方使用该函数,因为它是匿名的.

Isn't the second example, easier to read/understand? Now, I realize that these are very simple examples but the point I'm trying to get at is that I feel that anonymous functions make the code look cluttered and hard to understand. There are braces and parentheses everywhere and you can't use that function anywhere else since it's anonymous.

函数的全部意义难道不是能够将您的代码组织成不同的模块,使您的代码看起来更简洁,使调试更容易并避免冗余代码吗?

Isn't the whole point of functions to be able to organize your code into distinct modules to make your code look cleaner, to make debugging easier and to avoid redundant code?

为什么有人会使用匿名函数而不是命名函数?他们的目的是什么?

Why would anyone use anonymous functions over named functions? What purpose do they serve?

推荐答案

匿名函数的要点在于您只需使用它们一次,而不必在其他地方定义它们(以便重用).它很简洁,因为它们就在使用它们的地方(在特定上下文中).

The point of anonymous functions is that you use them only once instead of having to define them somewhere else (for reuse). It is neat because they are right where they are to be used (in a certain context).

使用它们是您的选择.如果你不喜欢他们..不要!

It is your choice to use them. If you don't like them.. don't!

这篇关于为什么使用匿名函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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