Wednesday, January 27, 2010

JS local functions: anonymous vs. named

I could not see clearly any reasons to keep anonymous code but the disadvantages are obvious.
If you could put some arguments, please comment.

Use of anonymous functions.
{// scope begins
    … // logic mixed with declarations
_ajaxify = function(cont) {
            return ;
}// scope ends

It creates anonymous function. As result you:
·         cannot see in debugger what really has been in call stack.
·         It clutters the actual code logic with mixed-in local function declarations
·         Create dependency of where the variable been initialized (if at all)

Solution: use named functions instead:

{// scope begins
    //logic implementation
    // local functions declarations 
_ajaxify( cont ) {
            return ;
function … 

}// scope ends

·         There is no performance gain from delayed function load in var locFunc=function(){…}. See the performance tests:  500 | 1000 | 3000 | 10000 (compare Var versus Fun, like 0/2 or 4/6). Beware the last two: they are JS stress tests! 
Smaller JS footprint function locFunc(){…} – is 5 character shorter. Could be significant for large number of small functions.


Related blog on subject:

No comments:

Post a Comment