我最近注意到 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模板网!
用于创建头像的 jQuery/JavaScript 库?jQuery/JavaScript Library for avatar creation?(用于创建头像的 jQuery/JavaScript 库?)
如何做以下掩码输入问题?How to do following mask input problem?(如何做以下掩码输入问题?)
使用 DropKick Javascript 设置值/标签的问题Issues Setting Value/Label Using DropKick Javascript(使用 DropKick Javascript 设置值/标签的问题)
如何对 jquery 插件中的私有方法进行单元测试?how to unit-test private methods in jquery plugins?(如何对 jquery 插件中的私有方法进行单元测试?)
stellar.js - 为垂直滚动网站配置偏移量/对齐元素stellar.js - configuring offsets / aligning elements for a vertical scrolling website?(stellar.js - 为垂直滚动网站配置偏移量/对齐元素?)
jQuery 屏蔽输入插件.当文本框获得焦点时选择所有jQuery masked input plugin. select all content when textbox receives focus(jQuery 屏蔽输入插件.当文本框获得焦点时选择所有内容)