为什么 JavaScript 需要以“;"开头?

我最近注意到 Web 上的很多 JavaScript 文件都以 ; 开头,紧跟在评论部分之后.

I have recently noticed that a lot of JavaScript files on the Web start with a ; immediately following the comment section.

例如,这个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 文件中也看到了这种约定.

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?

推荐答案

我想说,因为脚本经常被连接和缩小/压缩/发送在一起,所以最后一个人有可能有类似的东西:

I would say since scripts are often concatenated and minified/compressed/sent together there's a chance the last guy had something like:

return {
   'var':'value'
}

在最后一个脚本的末尾没有 ; 在末尾.如果你有一个 ; 在你的开头,它是安全的,例如:

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:

return {
   'var':'value'
}
;(function( $ ){ //Safe (still, screw you, last guy!)

<小时>

return {
   'var':'value'
}
(function( $ ){ //Oh crap, closure open, kaboom!

<小时>

return {
   'var':'value'
};
;(function( $ ){ //Extra ;, still safe, no harm

相关文章