Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - 为什么JavaScript需要以“;”开头?(Why does the JavaScript need to start with “;”?)

I have recently noticed that a lot of JavaScript files on the Web start with a ;

(我最近注意到Web上的很多JavaScript文件都以a开头;)

immediately following the comment section.

(紧跟评论部分。)

For example, this jQuery plugin's code starts with:

(例如, 这个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( $ ){

Why does the file need to start with a ;

(为什么文件需要以a开头;)

?

(?)

I see this convention in server-side JavaScript files as well.

(我也在服务器端JavaScript文件中看到了这种约定。)

What are the advantages and disadvantages of doing this?

(这样做的优点和缺点是什么?)

  ask by TK. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...