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 :)
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:
Vs.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With