Question

Taking the jQuery framework for example, if you run code like this:

$(document).ready(function init() { foo.bar(); });

The stack trace you get in Firebug will look like this:

init()
anonymous()
anonymous([function(), init(), function(), 4 more...], function(), Object name=args)
anonymous()
anonymous()

As you can see, it's not very readable, because you have to click on each function to find out what it is. The anonymous functions would also show up as (?)() in the profiler, and they can lead to the "cannot access optimized closure" bug. It seems to me that these are good reasons to avoid them. Then there's the fact that ECMAScript 5 will deprecate arguments.callee in its strict mode, which means it won't be possible to reference anonymous functions with it, making them a little less future-proof.

On the other hand, using named functions can lead to repetition, e.g.:

var Foo = {
    bar: function bar() {}
}

function Foo() {}

Foo.prototype.bar = function bar() {}

Am I correct in thinking that this repetition is justified in light of the debugging convenience named functions provide, and that the prevalence of anonymous functions in good frameworks like jQuery is an oversight?

Was it helpful?

Solution 2

I found the answer to my question in this very informative article. Firstly, it turns out that I was right about named functions being more desirable, but the solution is not as simple as adding identifiers to all anonymous functions. The main reason for this is JScript implementing function expressions in a very broken way.

Secondly, there is a distinction between function statements and expressions. An anonymous function is just a function expression with the identifier omitted, and adding an identifier (naming it) wouldn't make it a statement (except in JScript, which is why it's broken). This means that all of the other answers were off mark.

OTHER TIPS

I agree there are certain downsides to using anonymous methods in JavaScript/EMCAScript. However, don't overlook how they should be used. For simple one liners that you want to pass to another function, they are often excellent.

But for me anonymous functions are more readable in the source code, because I am sure they are only used there.

Anonymous functions are very convenient. A better fix to this problem, instead of naming the functions, would be if firebug told you on which line in which file the anonymous function was created.

init()
anonymous() // application.js, line 54
anonymous() // foo.js, line 2

And the stack trace is the only place where anonymous functions are a problem imo.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top