简体   繁体   English

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

[英]When should I use a semicolon after curly braces?

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?什么时候在花括号后使用分号合适?

You use a semicolon after a statement.在语句后使用分号。 This is a statement:这是一个声明:

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

because it is a variable assignment (ie 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 , do and while loops.注意:没有分号的相同块结构也适用于fordowhile循环。

It matters too when you intend to minify your code.当您打算缩小代码时,这也很重要。

So I personally add one after every } where automatic semicolon insertion (ASI) would insert one.所以我个人在每个}之后添加一个,其中自动分号插入(ASI) 会插入一个。

I wrote a post about ASI in JavaScript .我写了一篇关于JavaScript 中的 ASI的文章。

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

You never need to;你永远不需要; you always can (except before else and while ).你总是可以(除了之前elsewhile )。

Explanation:解释:

Unfortunately, JavaScript semicolons are optional.不幸的是,JavaScript 分号是可选的。
Therefore, you never need to add a semicolon.因此,您永远不需要添加分号。

It is (very) good practice to terminate every statement with a semicolon.用分号终止每个语句是(非常)好的做法。
The only statements that end with a } are statements ending with an object literal (eg JSON) or function expression.唯一以}结尾的语句是以对象字面量(例如JSON)或函数表达式结尾的语句。

Therefore, best practice is to put semicolons after the following two braces (only):因此,最佳做法是在以下两个大括号后放置分号(仅):

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

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使用参数值 3 运行 testMethod
testMethod type: number, value: 2 testMethod 类型:数字,值:2
Instantiating testClass实例化 testClass
I'm Bill"我是比尔”

...plus a JavaScript error reported by the browser: testOb.testMethod is not a function ...加上浏览器报告的 JavaScript 错误: testOb.testMethod is not a function

This is certainly not what we intended.这当然不是我们想要的。 Why is testMethod running immediately, before we have even instantiated the class?为什么testMethod立即运行,甚至在我们实例化类之前? And why does it no longer exist when we want to call it as a member method?当我们想把它作为成员方法调用时,为什么它不再存在?

What is happening is that testMethod is being assigned not our function definition, but the return value of the function definition.发生的事情是testMethod被分配的不是我们的函数定义,而是函数定义的返回值。 And the function definition itself is being run anonymously.并且函数定义本身是匿名运行的。 This is how:这是如何:

  1. The testClass constructor and the member method report are successfully defined/assigned. testClass构造函数和成员方法report成功定义/分配。
  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 of testMethod to become an anonymous function that is invoked immediately, and the return value of the following anonymous function becomes its parameter list.因为testMethod定义后没有分号,所以后面的自调用函数的()变成了一个调用操作符,导致我们认为是我们定义的testMethod变成了一个立即调用的匿名函数,而以下匿名函数的返回值成为其参数列表。 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 not the function definition.由于我们预期的函数定义返回 2,因此分配给testMethod是这个 2,而不是函数定义。 This is confirmed by our printing of the type and value of testMethod .我们打印的testMethod的类型和值证实了这一点。
  4. Now testClass is successfully instantiated as testOb and its report method works as intended, proving that the class definition is otherwise intact.现在testClass成功实例化为testOb并且它的report方法按预期工作,证明类定义在其他方面是完整的。
  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.当我们尝试调用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的定义testMethod加上一个分号,它将把它的赋值和自调用函数的调用分开,我们就会得到我们期望的结果:

"Running self-invoking function "运行自调用函数
Instantiating testClass实例化 testClass
I'm Bill我是比尔
Running testMethod with parameter value 4"使用参数值 4" 运行 testMethod



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.但我建议,既然问题是由于赋值语句末尾没有分号,我们或许应该养成这样的习惯,在这样定义函数之后总是放一个分号。 ie all of my functions above should have a semicolon after the closing brace, because they are all assignments of anonymous functions.即我上面的所有函数在右大括号后都应该有一个分号,因为它们都是匿名函数的赋值。

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 + "!"
    );
  };
}

Consider this code:考虑这个代码:

// This will break code

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

It will return "Property of object [object Object] is not a function".它将返回“对象的属性 [对象对象] 不是函数”。 Because it will actually be executed as:因为它实际上会被执行为:

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

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.在闭合支架之后使用它们,或者穿吊带和腰带都没有坏处,但它看起来确实有点书呆子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM