当前位置: 动力学知识库 > 问答 > 编程问答 >

Is there any advantage to define function name in "var new_function = function name(){};" in 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 :)

网友答案:

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:

  • Named Function Demystified
分享给朋友:
您可能感兴趣的文章:
随机阅读: