3
A
回答
5
这是因为ASI(自动分号插入)允许您避免使用分号。
例如,你可以写这样的代码,并没有错误:
var a = 1
a.fn = function() {
console.log(a)
}
看到了吗?没有一个分号。
但是,有些情况下分号未插入。基本上,在真实项目中,有一种情况不是:下一行以括号开头。
JavaScript解析器将把下一行作为参数,而不是自动添加分号。
例子:
var a = 1
(function() {})()
// The javascript parser will interpret this as "var a = 1(function() {})()", leading to a syntax error
为了避免这种情况,有几种方法:
- 在一行的开头添加一个分号用括号开始(这是在告诉你的代码完成)
使用以下结构:
!function() {}()
1
JavaScript有自动分号插入(见ECMAScript Language Specification节7.9):
There are three basic rules of semicolon insertion:
- When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
- The offending token is separated from the previous token by at least one LineTerminator.
- The offending token is
}
.- When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
通常你可以省略JavaScript文件中的最后一个分号(第二条规则)。如果您的应用程序通过合并多个文件来创建JavaScript代码,则会导致语法错误。由于;
本身就是空的语句,因此可以使用它来防止此类语法错误。
0
很好的解释可以在这里找到:
http://mislav.uniqpath.com/2010/05/semicolons/
(见第 “唯一真正的陷阱没有分号编码时”)
var x = y
(a == b).print()
被评估为
var x = y(a == b).print()
底线,这是一个很好的做法,在每一行之前加上一个分号,以(characther 。
相关问题
- 1. 函数之前的&符号(&)是什么意思?
- 2. 函数参数之后和函数体之前的char * in_str是什么意思?
- 3. C#中变量名之前的@符号是什么意思?
- 4. 新操作符之前的括号 - 是什么意思?
- 5. 类声明之前的方括号是什么意思?
- 6. 冒号是什么意思?
- 7. 符号“⊇”是什么意思?
- 8. &符号是什么意思?
- 9. 是什么意思:是什么意思?
- 10. subs或函数参数中的问号是什么意思?
- 11. “$”在Delphi中的数字之前是什么意思?
- 12. 符号“#!”是什么意思?在Python中的意思是?
- 13. BASIC:函数名称末尾的感叹号是什么意思?
- 14. python字符串之前的b前缀是什么意思?
- 15. 这个C++函数是什么意思?
- 16. :: at函数名是什么意思?
- 17. 函数调用前面的类型声明是什么意思
- 18. &&在函数签名的末尾(在右括号之后)是什么意思?
- 19. 在“泛型”类型参数之前,“out”是什么意思?
- 20. JSP中的$符号是什么意思
- 21. JavaScript中的$符号是什么意思?
- 22. Javascript中的符号“:”是什么意思?
- 23. 闭包的括号是什么意思?
- 24. /Zc:wchar_t-中的减号是什么意思?
- 25. XSLT中的冒号是什么意思?
- 26. TSQL中的“#”符号是什么意思?
- 27. URL中的冒号是什么意思?
- 28. Linux中的符号^ \意思是什么
- 29. JQuery的“$”符号是什么意思?
- 30. 函数原型是什么意思与&符号?
这是一个分号。如果在另一个缺少尾随分号的文件之后导入文件,可能会出现这种情况。 – Pointy 2012-04-06 14:12:16
@积分谢谢。你可以将它发布在答案中,以便我可以接受它来结束这个问题。 – wong2 2012-04-06 14:15:55