简体   繁体   English

在javascript中的“var new_function = function name(){};”中定义函数名是否有任何优势?

[英]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: 我正在运行一个程序来改变我的javascript代码的某些部分,当它在var的声明中作为一个像这样的函数的bug:

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. 代码本身有效,但我只是想知道是否可以删除我发现的所有函数的“名称”(因为它不会在分析我的javascript的其他问题中破坏它)或者它是否可以是用它,我看不到。

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: 注意:首次出现的原始文件位于jquery-1.6.4.js中:

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 :) ty提前任何帮助:)

The name identifier of Function Expressions, is accessible only within the function itself. 函数表达式的name标识符只能在函数本身中访问。

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. 在你的jQuery示例中,甚至没有使用init标识符,所以我认为将函数命名为调试目的的唯一优势是,调试器将能够在一长串调用中显示函数名称。

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: 存在缺点,IE <= 8上的长期错误使命名函数表达式将名称标识符泄漏到其封闭范围,此外,创建两个函数对象,例如:

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, eg: 为避免此错误的副作用,有几种解决方法,例如,在立即调用的函数内部工作,在该范围内创建函数声明,并返回它,例如:

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

  return init;
})();

And other similar ways, I would recommend you to check the following article: 和其他类似的方法,我建议你查看以下文章:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM