繁体   English   中英

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

[英]Why does the JavaScript need to start with “;”?

我最近注意到Web上的很多JavaScript文件都以a开头; 紧跟评论部分。

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

为什么文件需要以a开头; 我也在服务器端JavaScript文件中看到了这种约定。

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

我会说因为脚本经常连接和缩小/压缩/一起发送,所以最后一个人有可能有这样的事情:

return {
   'var':'value'
}

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

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

我相信(虽然我不确定,所以请不要抨击我),这将确保关闭来自不同文件的任何先前声明。 在最坏的情况下,这将是一个空语句,但在最好的情况下,当未完成的语句实际来自上面时,它可以避免尝试追踪此文件中的错误。

考虑这个例子:

function a() {
  /* this is my function a */
}
a()
(function() {
  /* This is my closure */
})()

会发生什么,它将被评估如下:

function a() {
  /* this is my function a */
}
a()(function() {})()

所以什么都a是返回时,将被视为试图初始化函数。

这主要是为了防止在尝试将多个文件连接到一个文件时出错:

a.js

function a() {
  /* this is my function a */
}
a()

b.js

(function() {
  /* This is my closure */
})()

如果我们将这些文件连在一起会导致问题。

所以记得把你的; (也许还有一些其他地方.Btw.var var a = 1;;;var b = 2;;;;;;;;;var c = a+b;是完全有效的JavaScript

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM