Why use named function expressions?

2018-12-31 05:17发布

We have two different way for doing function expression in JavaScript:

Named function expression (NFE):

var boo = function boo () {
  alert(1);
};

Anonymous function expression:

var boo = function () {
  alert(1);
};

And both of them can be called with boo();. I really can't see why/when I should use anonymous functions and when I should use Named Function Expressions. What difference is there between them?

5条回答
与君花间醉酒
2楼-- · 2018-12-31 05:31

If a function is specified as a Function Expression, it can be given a name.

It will only be available inside the function (except IE8-).

var f = function sayHi(name) {
  alert( sayHi ); // Inside the function you can see the function code
};

alert( sayHi ); // (Error: undefined variable 'sayHi')

This name is intended for a reliable recursive function call, even if it is written to another variable.

In addition, the NFE (Named Function Expression) name CAN be overwritten with the Object.defineProperty(...) method as follows:

var test = function sayHi(name) {
  Object.defineProperty(test, 'name', { value: 'foo', configurable: true });
  alert( test.name ); // foo
};

test();

Note: that with the Function Declaration this can not be done. This "special" internal function name is specified only in the Function Expression syntax.

查看更多
不流泪的眼
3楼-- · 2018-12-31 05:37

In the case of the anonymous function expression, the function is anonymous — literally, it has no name. The variable you're assigning it to has a name, but the function does not. (Update: That was true through ES5. As of ES2015 [aka ES6], often a function created with an anonymous expression gets a true name, read on...)

Names are useful. Names can be seen in stack traces, call stacks, lists of breakpoints, etc. Names are a Good Thing™.

You do have to beware of named function expressions in older versions of IE (IE8 and below), because IE mistakenly creates two completely separate function objects at two completely different times (more in my blog article Double take). If you need to support IE8, it's probably best to stick with anonymous function expressions or function declarations, but avoid named function expressions.

As of ES2015, though, a lot of "anonymous" function expressions create functions with names, and this was predated by various modern JavaScript engines being quite smart about inferring names from context. In ES2015, your anonymous function expression results in a function with the name boo. This is strewn throughout the spec rather than being defined in one place with a bunch of rules: Search for occurrences of "SetFunctionName", currently found in:

The short version is basically any time an anonymous function expression appears on the right-hand side of something like an assignment or initialization, like:

var boo = function() { /*...*/ };

(or it could be let or const rather than var), or

var obj = {
    boo: function() { /*...*/ }
};

or

doSomething({
    boo: function() { /*...*/ }
});

(those last two are really the same thing), the resulting function will have a name (boo, in the examples).

There's an important, and intentional, exception: Assigning to a property on an existing object:

obj.boo = function() { /*...*/ }; // <== Does not get a name

This was because of information leak concerns raised when the new feature was going through the process of being added; details in my answer to another question here.

查看更多
春风洒进眼中
4楼-- · 2018-12-31 05:37

Using named function expressions is better, when you want to be able to reference the function in question without having to rely on deprecated features such as arguments.callee.

查看更多
宁负流年不负卿
5楼-- · 2018-12-31 05:52

Naming functions is useful if they need to reference themselves (e.g. for recursive calls). Indeed, if you are passing a literal function expression as an argument directly to another function, that function expression cannot directly reference itself in ES5 strict mode unless it is named.

For example, consider this code:

setTimeout(function sayMoo() {
    alert('MOO');
    setTimeout(sayMoo, 1000);
}, 1000);

It would be impossible to write this code quite this cleanly if the function expression passed to setTimeout were anonymous; we would need to assign it to a variable instead prior to the setTimeout call. This way, with a named function expression, is slightly shorter and neater.

It was historically possible to write code like this even using an anonymous function expression, by exploiting arguments.callee...

setTimeout(function () {
    alert('MOO');
    setTimeout(arguments.callee, 1000);
}, 1000);

... but arguments.callee is deprecated, and is outright forbidden in ES5 strict mode. Hence MDN advises:

Avoid using arguments.callee() by either giving function expressions a name or use a function declaration where a function must call itself.

(emphasis mine)

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 05:55

You should always use NAMED function expressions.

  1. You can use the name of that function when you need recursion.

2.Anonymous Functions doesn't help when debugging as you can't see the name of the function that causes problems.

3.When you do not name a function, later on its harder to understand what its doing.Giving it a name makes it easier to understand.

var foo = function bar() {
 //some code...
};
foo();
bar(); // Error!

Here, for example, because the name bar is used within a function expression, it doesnt get declared in the outer scope.With named function expressions, the name of the function expression is enclosed within its own scope.

查看更多
登录 后发表回答