立即函数调用语法 [英] Immediate function invocation syntax

查看:118
本文介绍了立即函数调用语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 JSLint 选项,实际上是一个好的部分,[需要] parens around immediately调用,意味着构造

There is a JSLint option, one of The Good Parts in fact, that "[requires] parens around immediate invocations," meaning that the construction

(function () {

  // ...

})();

需要写成

(function () {

  // ...

}());

我的问题是这个 - 有谁可以解释为什么第二种形式可能被认为更好?它更有弹性吗?不容易出错?它比第一种形式有什么优势?

My question is this -- can anyone explain why this second form might be considered better? Is it more resilient? Less error-prone? What advantage does it have over the first form?

自从提出这个问题以来,我已经明白了拥有这个问题的重要性功能值和功能值之间的清晰视觉区别。考虑立即调用的结果是赋值表达式的右侧的情况:

Since asking this question, I have come to understand the importance of having a clear visual distinction between function values and the values of functions. Consider the case where the result of immediate invocation is the right-hand side of an assignment expression:

var someVar = (function () {

  // ...

}());

虽然最外面的括号在语法上是不必要的,但是左括号给出了前面的指示,即值是赋值是函数本身,而是调用函数的结果。

Though the outermost parentheses are syntactically unnecessary, the opening parenthesis gives an up-front indication that the value being assigned is not the function itself but rather the result of the function being invoked.

这类似于Crockford关于构造函数大写的建议 - - 它可以作为任何查看源代码的人的视觉提示。

This is similar to Crockford's advice regarding capitalization of constructor functions -- it is meant to serve as a visual cue to anyone looking at the source code.

推荐答案

来自Douglass Crockford的风格会议指南 :(搜索立即调用)

From Douglass Crockford's style convention guide: (search for "invoked immediately")

当要立即调用一个函数时,整个调用表达式应该包含在parens中,这样很明显生成的值是函数的结果,而不是函数本身。

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

所以,基本上,他觉得这个区别更清楚了函数值和函数值之间的关系。所以,这是一个风格问题,而不是代码本身的实质性差异。

So, basically, he feels it makes more clear the distinction between function values, and the values of functions. So, it's an stylistic matter, not really a substantive difference in the code itself.

更新参考,旧PPT不再存在

这篇关于立即函数调用语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆