开发者

How should closures be formatted?

I ran a script through JSLint and it picked out a specific issue with parenthesis placement.

I had written:

(function(){})();

And it was suggested to use:

(function(){}());

I'm curious as to what bugs or issues this particular change fixes. I would assume that because JSLint picked it out as an issue, there must be an issue for someone.

Expanded forms:

(
  function (p) {
    ...code...
  }
)(param); //parameters after the parens

-vs-

(
  function (p) {
    ...code...
  }(param)开发者_Go百科 //parameters within the parens
);


The specific issue JSLint is trying to fix relates to a lack of closing ; which can cause a bug where a function is interpreted as an argument:

(function A( arg ){
    // stuff
})

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

Is perfectly valid, B is passed to A as arg. However, this is often not the intended case as often these are meant to be self-executing and the trailing () were forgotten. The suggested syntax removes any confusion that you may have accidentally forgotten to execute your function as intended.

For what it's worth, I pretty much always use the first syntax as well; habit.


According to Crockford on http://www.yuiblog.com/crockford/ (can't remember which video, but I think it's towards the beginning) it is pure styling to help make it easier to read and is not related to bugs or issues.

Edit:

I think it is in Act III: Function the Ultimate

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜