Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are named functions underrated in JavaScript?

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?

like image 622
slikts Avatar asked Oct 27 '09 10:10

slikts


2 Answers

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.

like image 194
C. Ross Avatar answered Sep 20 '22 18:09

C. Ross


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.

like image 27
slikts Avatar answered Sep 23 '22 18:09

slikts