开发者

A simple question about Javascript functions, differences in invocation/definition

Can someone please explain the difference between the following function definitions?

var alertMessage = function alertMessage(message) {
  alert(message);
}

var alertMessage = function(message) {
  alert(message);
}

What are 开发者_开发问答the implications of each? Thanks!


Both are function expressions, basically the difference is that the first is named, and the second one is anonymous.

For example:

var test = function test(message) {
  alert(message);
};

var test1 = function(message) {
  alert(message);
};

test.name; // "test"
test1.name // "" or "anonymous"

Note: The name property of function objects exist on some implementations, but it's non-standard.

Also, the name of function expressions it's useful for debugging, as you can inspect the call stack to see where you are.

This identifier is only accessible from inside the FunctionBody itself:

(function foo(){
  typeof foo; // "function"
})();
typeof foo; // "undefined"

However there is a bug on the JScript implementation (in all versions of IE), which this name is leaked to its enclosing scope.


Both definitions are function expressions, as opposed to function declarations, or functions created by the Function constructor. They both assign a function to the variable alertMessage. The difference is that the first function is named, while the second is anonymous.

Named functions are usually used in function declarations, eg

function alertMessage(message) { ... }

In that case, the function declaration creates a variable in the current scope called alertMessage that references that function. Function declarations are hoisted to the top of the current scope, so you can call declared functions before they're defined in you js file.

A named function used in a function expression (such as the original question) does not create this variable, or get hoisted to the top of the execution scope, so by convention most function expressions are anonymous. The only benefits to naming a function expression are that the name variable is bound within the function (although as CMS mentions, this is implementation dependent) and the function name is output from the function's toString method. This can be useful during debugging (rather than having Firebug output (?) for a huge list of anonymous function calls).

Much more detail at MDC

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜