为什么 JavaScript 需要以“;”开头?
我最近注意到,网络上的许多 JavaScript 文件都以 ;
开头,紧跟在注释部分之后。
例如,此 jQuery 插件 代码开头为:
/**
* jQuery.ScrollTo
* Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 9/11/2008
.... skipping several lines for brevity...
*
* @desc Scroll on both axes, to different values
* @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
*/
;(function( $ ){
为什么文件需要以 ;?我也在服务器端 JavaScript 文件中看到了这种约定。
这样做的优点和缺点是什么?
I have recently noticed that a lot of JavaScript files on the Web start with a ;
immediately following the comment section.
For example, this jQuery plugin's code starts with:
/**
* jQuery.ScrollTo
* Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
* Date: 9/11/2008
.... skipping several lines for brevity...
*
* @desc Scroll on both axes, to different values
* @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
*/
;(function( $ ){
Why does the file need to start with a ;
? I see this convention in server-side JavaScript files as well.
What are the advantages and disadvantages of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想说,由于脚本经常被连接并缩小/压缩/发送在一起,所以最后一个人有可能会遇到类似的情况:
在最后一个脚本的末尾没有
;
。如果你的开头有一个;
,那么它是安全的,例如:I would say since scripts are often concatenated and minified/compressed/sent together there's a chance the last guy had something like:
at the end of the last script without a
;
on the end. If you have a;
at the start on yours, it's safe, example:我相信(尽管我不确定,所以请不要攻击我)这将确保来自不同文件的任何先前声明都被关闭。在最坏的情况下,这将是一个空语句,但在最好的情况下,当未完成的语句实际上来自上面时,它可以避免尝试跟踪此文件中的错误。
I believe (though I am not certain, so please don't pounce on me) that this would ensure any prior statement from a different file is closed. In the worst case, this would be an empty statement, but in the best case it could avoid trying to track down an error in this file when the unfinished statement actually came from above.
考虑这个例子:
将会发生的情况是,它将像这样进行评估:
因此,返回的任何
a
都将被视为试图初始化的函数。这主要是为了防止在尝试将多个文件连接到一个文件中时出现错误:
a.js
b.js
如果我们将这些文件连接在一起,则会导致问题。
因此,请记住将
;
放在(
前面,也许还有其他一些地方。顺便说一句。var a = 1;;;var b = 2; ;;;;;;;;var c = a+b;
是完全有效的 JavaScriptConsider this example:
What will happen is that it will be evaluated like this:
So what ever
a
is returning will be treated as a function an tried to be initialized.This is mostly to prevent errors when trying to concat multiply files into one file:
a.js
b.js
If we concat these files together it will cause problems.
So therefore remember to put your
;
in front of(
and maybe also a few other places. Btw.var a = 1;;;var b = 2;;;;;;;;;var c = a+b;
is perfectly valid JavaScript