我有一个很长的脚本很好地包装在 (function() {/.../})()
中以避免各种名称污染。它是 100% 零警告打字。
我发现 Google Closure 编译器通过在全局命名空间中重新定义 i
和 j
开始,这感觉既不必要又危险,特别是因为我正在编译一个脚本对命名空间的零干扰。 (编译后的脚本以 var i=null,j=!1;
开头,我相信是出于紧凑的原因)。
我能想到一种解决方法,即使用 --output_wrapper
对其进行包装,但我想不出 Google 会像这样污染命名空间的原因。
有没有?
最佳答案
编译器希望为它提供所有 相关的 JavaScript,这样它就不必担心与其他脚本发生冲突。因此它假定它可以解包“不必要的”匿名函数。
来自FAQ :
When using Advanced Optimizations, Closure Compiler adds new variables to the global scope. How do I make sure my variables don't collide with other scripts on the page?
Closure Compiler's advanced optimizations mode assumes that it's ok to add new variables to the global scope.
In JavaScript, it's often standard practice to wrap your code in an anonymous function, so that variables don't pollute the global scope. Closure Compiler has an
--output_wrapper
flag for exactly this purpose. Invoking it as--output_wrapper "(function() {%output%})();"
will wrap your code in an anonymous function at compile-time.Closure Compiler users often find it easier and simpler to do this wrapping at compile-time, rather than writing the anonymous function wrapper in the original source code.
关于javascript - 为什么 Google Closure Compiler 在原始命名空间为空时向全局命名空间添加变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18449503/