Are anonymous functions a bad practice in JavaScript?

I was reading that using anonymous functions in javascript is bad practice, because it can make debugging a pain, but I haven't seen this for myself. Are anonymous functions in JavaScript really bad practice and, if so, why?


Nope, anonymous functions are used all over the place in JavaScript across the web. It may make debugging a little more difficult in spots, but not nearly enough to say that they shouldn't be used.

For example, JQuery makes extensive use of them.

There are a lot of times when you want to use them over formally declared functions, such as when you want to limit their scope.


I am going to go against the flow a little here and make the case that anonymous functions are indeed bad practice even though they are widely used.

1) Anonymous functions cannot be reused.

2) Anonymous functions, by definition, do not have a name and so do not describe what they do. Which is to say the code is not self documenting.

3) Anonymous functions cannot be tested in isolation with a unit testing framework.

4) I personally think they make code more difficult to read and debug. Though your experience may vary.

I do think there are situations where an anonymous function is the best choice and as a general rule in order to avoid the above downsides I almost always name my functions.


I would say the contrary, lambdas ( alias ) make some expressions much more succinct. If you're binding multiple event handlers to multiple events it would be tedious giving a function name to each and every event handler, for example.

It's more helpful and time-conserving than not, even if it makes debugging a little bit harder but I rarely struggle with debugging because a function is anonymous. And you should use JSLint to make your life easier when coding.

链接地址: http://www.djcxy.com/p/17262.html

上一篇: JavaScript中的函数表达式与声明之间有什么区别?

下一篇: 匿名函数在JavaScript中是不好的做法吗?