問題描述
我最近注意到 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
這篇關于為什么 JavaScript 需要以“;"開頭?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!