开发者

"function foo(bar) { }" versus "foo = function(bar) { }" [duplicate]

This question already has answers here: var functionName = function() {} vs function functionName() {} 开发者_高级运维 (41 answers) Closed 8 years ago.
function foo(bar) {
    // ...
}

and

foo = function(bar) {
    // ...
};

What is the benefit of one versus the other? The main benefit I see in the latter is not running into errors with a function name already being defined. However, there may be other benefits or drawbacks that aren't obvious. What are they (if any)?


This has been asked a few times, this seems to be the best one.


There are other things that you can do with an anonymous function other than assigning it to a variable. You can for example execute it right away:

(function() { ... })();

This is sometimes used to create a scope for the code. Anything declared in the scope is local to it, and you can return a result to the code outside:

var a = (function() {

  var answer = 42;

  function display() { window.alert(answer); };

  return display;

})();

Now the variable a contains a function that displays the value of the variable answer, but the variable answer is local to the scope:

a(); // displays the value
display(); // not available
window.alert(answer); // not available

This pattern is for example used to create plugins for jQuery:

(function($) {

  $.fn.blackText = function() {
    return this.css('color', '#000');
  };

}(jQuery);

The jQuery object is sent into the scope as the $ parameter, that way the code in the scope can use the $ shortcut even if it has been turned off (using noConflict) outside the scope.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜