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

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

问题描述


可能重复:

我一直在阅读/编写一些基本的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天全站免登陆