简体   繁体   中英

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

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:

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.

 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 :

Note : You should avoid using arguments.callee() and just give every function (expression) a name.

Warning : The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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