Javascript 什么时候应该在花括号后使用分号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2717949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:37:29  来源:igfitidea点击:

When should I use a semicolon after curly braces?

javascriptsyntax

提问by Rob Gibbons

Many times I've seen a semicolon used after a function declaration, or after the anonymous "return" function of a Module Pattern script. When is it appropriate to use a semicolon after curly braces?

我多次看到在函数声明之后或模块模式脚本的匿名“返回”函数之后使用分号。什么时候在花括号后使用分号合适?

回答by cletus

You use a semicolon after a statement. This is a statement:

在语句后使用分号。这是一个声明:

var foo = function() {
  alert("bar");
};

because it is a variable assignment (i.e. creating and assigning an anonymous function to a variable).

因为它是一个变量赋值(即创建一个匿名函数并将其赋值给一个变量)。

The two things that spring to mind that aren't statements are function declarations:

两个不是语句的东西是函数声明:

function foo() {
  alert("bar");
}

and blocks:

和块:

{
  alert("foo");
}

Note:that same block construct without semi-colon also applies to for, doand whileloops.

注意:没有分号的相同块构造也适用于for,dowhile循环。

回答by alex

It matters too when you intend to minify your code.

当您打算缩小代码时,这也很重要。

So I personally add one after every }where ASI would insert one.

所以我个人}在 ASI 会插入一个的每个位置之后添加一个。

I wrote a post about ASI in JavaScript.

我写了一篇关于JavaScript 中的 ASI的文章。

回答by Web_Designer

Don't use a semicolon:

不要使用分号:

...if it's just your every-day function declaration:

...如果这只是您的日常函数声明:

function foo() {

} // No semicolon



Use a semicolon:

使用分号:

...if it's an assignment:

...如果这是一项任务:

var foo = function() {

}; // Semicolon


...or a self invoking function:


...或自调用函数:

(function () {

})(); // Semicolon

回答by SLaks

You never need to; you always can (except before elseand while).

你永远不需要;你总是可以(除了之前elsewhile)。

Explanation:

解释:

Unfortunately, Javascript semicolons are optional.
Therefore, you never need to add a semicolon.

不幸的是,Javascript 分号是可选的。
因此,您永远不需要添加分号。

It is (very) good practice to terminate every statementwith a semicolon.
The only statements that end with a }are statements ending with an object literal (e.g. JSON) or function expression.

用分号终止每个语句是(非常)好的做法。
唯一以 a}结尾的语句是以对象字面量(例如 JSON)或函数表达式结尾的语句。

Therefore, best practice is to put semicolons after the following two braces (only):

因此,最佳做法是在以下两个大括号后放置分号(仅):

var myFunc = function() { };
var myobject = { };

回答by Code83

If we have a self-invoking function, we need to put a semicolon before it, otherwise it becomes part of the previous assignment statement. Consider the following:

如果我们有一个自调用函数,我们需要在它前面放一个分号,否则它就成为前面赋值语句的一部分。考虑以下:

testClass = function(name) {
  document.write ("Instantiating testClass<br />");
  this.name = name;
}

testClass.prototype.report = function() {
  document.write ("I'm " + this.name + "<br />");
  return 1;
}

testClass.prototype.testMethod = function(param) {
  document.write ("Running testMethod with parameter value " + param + "<br />");
  return 2;
} // notice that there is no semicolon here

(function() {
  document.write ("Running self-invoking function<br />");
  return 3;
}());

if (typeof(testClass.prototype.testMethod) !== "function") {
  document.write ("testMethod type: " + typeof(testClass.prototype.testMethod));
  document.write (", value: " + testClass.prototype.testMethod + "<br />");
}
var testOb = new testClass("Bill");
testOb.report();
testOb.testMethod(4);


This will produce the following output:


这将产生以下输出:

"Running self-invoking function
Running testMethod with parameter value 3
testMethod type: number, value: 2
Instantiating testClass
I'm Bill"

“运行自调用函数
运行 testMethod 参数值为 3
testMethod 类型:数字,值:2
实例化 testClass
我是比尔”

...plus a JavaScript error reported by the browser: testOb.testMethod is not a function

This is certainly not what we intended. Why is testMethodrunning immediately, before we have even instantiated the class? And why does it no longer exist when we want to call it as a member method?

...加上浏览器报告的 JavaScript 错误:testOb.testMethod is not a function

这当然不是我们想要的。为什么testMethod在我们实例化类之前立即运行?当我们想把它作为成员方法调用时,为什么它不再存在?

What is happening is that testMethodis being assigned not our function definition, but the return value of the function definition. And the function definition itself is being run anonymously. This is how:

发生的事情是testMethod分配的不是我们的函数定义,而是函数定义的返回值。并且函数定义本身是匿名运行的。这是如何:

  1. The testClassconstructor and the member method reportare successfully defined/assigned.
  2. Because of the lack of a semicolon after the definition for testMethod, the ()surrounding the following self-invoking function becomes an invocation operator, which causes what we think is our definition oftestMethodto become an anonymous function that is invoked immediately, and the return value of the following anonymous function becomes its parameter list. This explains the order of printed output - our self-invoking function is run first as it is evaluated as a parameter.
  3. Since our intended function definition returns 2, it is this 2 that is assigned to testMethod, and notthe function definition. This is confirmed by our printing of the type and value of testMethod.
  4. Now testClassis successfully instantiated as testOband its reportmethod works as intended, proving that the class definition is otherwise intact.
  5. When we try to call testMethod, we are told by the interpreter that it is not a function - and rightly so, because it is a number with the value 2.
  1. testClass构造和部件的方法report被成功地定义/分配。
  2. 因为 for 的定义后面没有分号testMethod()后面的自调用函数就变成了一个调用操作符,导致我们认为我们定义的testMethod变成了一个立即调用的匿名函数,而这个函数的返回值下面的匿名函数成为它的参数列表。这解释了打印输出的顺序 - 我们的自调用函数首先运行,因为它被评估为参数。
  3. 由于我们预期的函数定义返回 2,因此分配给 的是这个 2 testMethod,而不是函数定义。我们打印的类型和值证实了这一点testMethod
  4. 现在testClass已成功实例化,testOb并且其report方法按预期工作,证明类定义在其他方面是完整的。
  5. 当我们尝试调用 时testMethod,解释器告诉我们它不是一个函数——这是正确的,因为它是一个值为 2 的数字。

If we put a semicolon after the definition of testMethod, it will separate its assignment from the calling of the self-invoking function, and we will have the result we expected:

如果我们在 的定义后面加一个分号testMethod,它将把它的赋值与自调用函数的调用分开,我们将得到我们期望的结果:

"Running self-invoking function
Instantiating testClass
I'm Bill
Running testMethod with parameter value 4"

“运行自调用函数
实例化 testClass
我是 Bill
Running testMethod 参数值为 4”



Or we could even put it directly before the anonymous function:



或者我们甚至可以将它直接放在匿名函数之前:

;(function() {...

But I suggest that since the problem is due to the lack of a semicolon at the end of an assignment statement, we should perhaps make a habit of always putting a semicolon after defining functions in this way. i.e. all of my functions above should have a semicolon after the closing brace, because they are all assignments of anonymous functions.

但我建议,既然问题是由于赋值语句末尾没有分号,我们或许应该养成这样定义函数后总是放分号的习惯。即我上面的所有函数都应该在右大括号后有一个分号,因为它们都是匿名函数的赋值。

回答by MarcNC

You also should use a semicolon after a curly bracket after returning a function within a function in Javascript.

在 Javascript 中返回函数内的函数后,您还应该在大括号后使用分号。

function watchOut(problem) {
  return function(number, location) { 
    alert("Be careful! There are " + problem +
          " today!\n" +

          number + " have been spotted at the " + location + "!"
    );
  };
}

回答by Kush

I know this thread is old but couldn't resist to share this code:

我知道这个线程很旧,但忍不住要分享这个代码:

// this will break code

a=b=c=d=e=1
a = b + c     //semicolon required here
(d + e).toString()

Will return "Property of object [object Object] is not a function". Because it will actually be executed as:

将返回“对象 [object Object] 的属性不是函数”。因为它实际上会被执行为:

a = b + c(d + e).toString()

回答by kennebec

Semicolons go at the end of lines that do not end in a curly brace or to separate statements on the same line. It does no harm to use them after a closing brace, or to wear suspenders and a belt, but it does look a little nerdy.

分号位于不以花括号结尾的行的末尾,或用于分隔同一行上的语句。在闭合支架之后使用它们,或者穿吊带和腰带都没有坏处,但它看起来确实有点书呆子。