var NAME = function NAME (){ };

In Javascript, one standard way to declare a function is as follows:

var add = function(a,b){
   return a+b;
};

However, when I repeat the function name on the right side of the syntax, I get no errors either.

var add = function add(a,b){
  return a+b;
};

What's going on in the second case?


There are two uses of the function keyword in Javascript: function declarations and function expressions. Function declarations don't allow anything to the left of the keyword, eg

function add(a,b){
    return a+b;
}

and they always require a name, eg add . Meanwhile, your examples invoke the other type, function expressions, which don't require a name (but can be named!) and always require something to their left, eg your

var add = function(a,b){
    return a+b;
};

or even a single parenthesis:

(function(a,b){
    return a+b;
})(1,2); // 3

So now that we've got some vocabulary down, what you've got in your second example, reprinted—

var add = function add(a,b){
    return a+b;
};

—is a function expression (namely, variable assignment into add ) whose function happens to be named.

Now, what's the purpose of this named function expression?

It's expressly for accessing the function within itself! According to MDN's documentation,

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).

Let's rename your add s so we can talk about things less confusingly:

var abc = function xyz(a,b){
    return a+b;
};

In the above, abc will be accessible in the outer scope, while xyz will not be. Meanwhile, vice versa: abc will not be accessible in the inner scope, while xyz will be.


This function

var add = function add(a,b){
  return a+b;
};

Could be interpreted roughly as

// the scope of outer `add` is here
var add = function (a, b) {
   var add = ...self... // something like that. the scope of this `add` is here

   return a + b;
}

In both the cases you are ended up having a function called add() .

But the following behavior is interesting against this backdrop.

var add = 1;
function add() {};

add();     //<-- Error not a function
链接地址: http://www.djcxy.com/p/96290.html

上一篇: JavaScript对象实例化选项

下一篇: var NAME = function NAME(){};