在 JavaScript 开头以分号开头的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7145514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the purpose of starting semi colon at beginning of JavaScript?
提问by benpalmer
Possible Duplicate:
What does the leading semicolon in JavaScript libraries do?
可能的重复:
JavaScript 库中的前导分号有什么作用?
I have noticed a lot of jQuery plugins start with
我注意到很多 jQuery 插件都是以
;(function(){ /* something in here */ })();
I just wondered what the beginning semi-colon was for, as well as the empty parentheses at the end.
我只是想知道开头的分号是什么,以及末尾的空括号是什么。
回答by James Gaunt
The semi-colon is there in case you include this script just after some 'bad' script that doesn't properly close off its last line with a semi-colon. In this case it's possible the two scripts would be combined and result in invalid code. For example if you are merging multiple script into a single response.
分号在那里,以防您在一些“坏”脚本之后包含此脚本,这些脚本没有用分号正确关闭其最后一行。在这种情况下,这两个脚本可能会组合在一起并导致无效代码。例如,如果您将多个脚本合并为一个响应。
The () at the end is executing the function. This is creating a closure. Private variables and methods can be declared within the scope of this function that cannot be accessed from outside the script.
最后的 () 正在执行函数。这是在创建一个闭包。私有变量和方法可以在这个函数的范围内声明,不能从脚本外部访问。
回答by slaphappy
This construct :
这个构造:
(function(){ /* something in here */ })()
Is used to create a new scope in Javascript.
用于在 Javascript 中创建新范围。
More info on function scope here.
Regarding the semicolon, I never seen it before. I think it's a security for when you concatenate several scripts, since semicolons are optional in some cases at the end of the file.
关于分号,我以前从未见过。我认为这是连接多个脚本时的安全性,因为在某些情况下,分号在文件末尾是可选的。