Why are anonymous functions used? [duplicate]

一世执手 提交于 2020-01-14 05:42:50

问题


Possible Duplicate:
What are the benefits to using anonymous functions instead of named functions for callbacks and paramaters in JavaScript event code?

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.

For example, something like:

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

versus:

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?


回答1:


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!




回答2:


Because if you don't need/want the name, there's no sense in cluttering the variable environment with unused names.


And FYI, this:

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

should be this:

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

...unless you changed your function so that it returns a function.

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

But as you see here, I again used an anonymous function, because there's no other use for it in its variable environment, except as the return value.



来源:https://stackoverflow.com/questions/13103649/why-are-anonymous-functions-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!