简体   繁体   English

在javascript中的函数声明中命名函数的好处是什么?

[英]What is the benefit of naming a function in a function declaration in javascript?

I have sometimes seen this pattern used 我有时看到这种模式

function foo() {
    this.bar = function bar() {
        // code
    }
}

What is the benefit/reason for naming the function rather than having it as an anonymous function? 给函数命名而不是将其作为匿名函数的好处/原因是什么?

To further illustrate/clarify: 为了进一步说明/澄清:

function foo() {
    this.bar = function bar() {
        bar.someVar = 1;
    }
}

Vs VS

function foo() {
    this.bar = function() {
        this.someVar = 1;
    }
}

Thanks 谢谢

I suppose fundamentally, you can answer your question with a question. 我想从根本上来说,您可以用一个问题来回答您的问题。 That question is, if you don't name the function how would you go about calling the function explicitly elsewhere? 问题是,如果不命名该函数,将如何在其他位置显式调用该函数?

Of course, the example you provided would still work without a name so I'd suggest that it's as much about personal preference on the part of the developer as it is about anything functional. 当然,您提供的示例在没有名称的情况下仍然可以使用,因此我建议,与开发人员的个人喜好和所有功能有关的事情一样多。 I personally like to name my functions for easier debugging, reuse and readability as well as for the usefulness of explicitly calling them. 我个人喜欢为函数命名,以便于调试,重用和可读性以及显式调用它们的有用性。

There are also the obvious performance benefits to be gained by creating functions once and reusing them. 通过一次创建函数并重新使用它们,还可以获得明显的性能优势。

The main benefit for naming the function is in allowing it to be self-referential , especially for recursion: 命名function的主要好处是允许它是自引用的 ,尤其是对于递归而言:

If you want to refer to the current function inside the function body, you need to create a named function expression. 如果要引用函数体内的当前函数,则需要创建一个命名函数表达式。 This name is then local only to the function body (scope). 这样,该名称仅在功能主体(作用域)中是局部的。 This also avoids using the non-standard arguments.callee property. 这也避免了使用非标准的arguments.callee属性。

 var math = { 'factorial': function factorial(n) { if (n <= 1) return 1; return n * factorial(n - 1); } }; 

That is, without it having to be aware of its holding object and referencing property name, which can change: 也就是说,无需知道其持有对象和引用属性名称即可更改:

// a contrived and hopefully unrealistic example

function foo() {
    this.bar = function () {
        return this.bar;
    };
}

console.log(new foo().bar());        // Function
console.log(new foo().bar.call({})); // undefined, `{}` doesn't have a `bar`

As previously noted, it's an available solution to the partial " outlawing " of arguments.callee : 如前所述,这是对arguments.callee的部分“ 取缔 ”的可用解决方案:

Note : You should avoid using arguments.callee() and just give every function (expression) a name. 注意 :应避免使用arguments.callee()而应为每个函数(表达式)命名。

Warning : The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode . 警告 :ECMAScript的第五版禁止在严格模式下使用arguments.callee()

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

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