Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any advantage to define function name in "var new_function = function name(){};" in javascript?

Tags:

javascript

I was running a program to change some parts of my javascript code when it bugged in the declaration of a var as a function like this:

var some_function = function name(args){
//do stuff
};

The code itself works, but I was just wondering if it's ok to remove the "name" for all functions that i find like this (for it doesn't break it in the other problem that analyzes my javascript) or if it could be any use for it that I can't see.

removing the "name":

var new_function = function(){/*do stuff*/};

Note: the original file where it first happen it was in jquery-1.6.4.js in:

jQuerySub.fn.init = function init( selector, context ) {
    if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
        context = jQuerySub( context );
    }

    return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};

ty for any help in advance :)

like image 704
Seeker Avatar asked Oct 07 '11 18:10

Seeker


1 Answers

The name identifier of Function Expressions, is accessible only within the function itself.

In your jQuery example the init identifier isn't even used, so I think the only advantage to name the function it's just for debugging purposes, a debugger will be able to show you the function name in a long stack of calls.

Compare:

anonymous functions on stack

Vs.

named functions on stack

Disadvantages exist, a long-standing bug on IE <=8 makes named function expressions to leak the name identifier to its enclosing scope, moreover, creating two function objects, for example:

var foo = function bar() {}; 

typeof bar; // "function" on IE
foo === bar; // false, two different objects

To avoid the side effects of this bug there are several workarounds, for example, to work inside an immediately called function, to create a function declaration within that scope, and return it, e.g.:

jQuerySub.fn.init = (function () {
  function init( selector, context ) {
    //...
  }

  return init;
})();

And other similar ways, I would recommend you to check the following article:

  • Named Function Demystified
like image 58
Christian C. Salvadó Avatar answered Oct 23 '22 05:10

Christian C. Salvadó