为什么JavaScript需要以“;"开头? [英] Why does the JavaScript need to start with ";"?

查看:93
本文介绍了为什么JavaScript需要以“;"开头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近注意到,在注释部分之后,网络上的许多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需要以“;"开头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆