javascript - 为什么 Google Closure Compiler 在原始命名空间为空时向全局命名空间添加变量?

标签 javascript google-closure-compiler google-closure

我有一个很长的脚本很好地包装在 (function() {/.../})() 中以避免各种名称污染。它是 100% 零警告打字。

我发现 Google Closure 编译器通过在全局命名空间中重新定义 ij 开始,这感觉既不必要又危险,特别是因为我正在编译一个脚本对命名空间的零干扰。 (编译后的脚本以 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/

相关文章:

javascript - "Invariant Violation: The navigation prop is missing for this navigator"怎么解决?

javascript - 如何让闭包编译器停止省略对象参数?

php - 关闭编译器执行中的PHP错误

javascript - Google API client for javascript是否兼容Closure高级模式编译?

javascript - 组件之间传递值

javascript - 给定一个点和一个平面,当平面缩放而不缩放点时,如何平移点以匹配平面?

javascript - 如何在鼠标滚动和右键单击上添加事件?

javascript - 使用 Google Closure Compiler 缩小用 Typescript 编写的 AngularJs 应用程序

javascript - 关闭编译器警告 `dangerous use of the global this object`?

javascript - 使用 Google Closure 的复选框