5

I have a long script nicely wrapped into a (function() {/.../})() to avoid all kind of name pollution. It is 100% typed with zero warning.

I found out that Google Closure compiler starts by redefining i and j in the global namespace which feels both unnecessary and dangerous, especially since I am compiling a script that has zero interference with the namespace. (the compiled script starts with var i=null,j=!1;, for compactness reasons I believe).

I can think of a work around which is to wrap it using the --output_wrapper but I can't think of a reason why Google would pollute the namespace like this.

Is there any?

4

1 回答 1

10

编译器期望它提供所有相关的 JavaScript,这样它就不必担心与其他脚本的冲突。因此它假设它可以解开“不必要的”匿名函数。

常见问题解答

使用高级优化时,闭包编译器将新变量添加到全局范围。如何确保我的变量不会与页面上的其他脚本发生冲突?

Closure Compiler 的高级优化模式假定可以将新变量添加到全局范围。

在 JavaScript 中,将代码包装在匿名函数中通常是标准做法,这样变量就不会污染全局范围。Closure Compiler 有一个--output_wrapper专门用于此目的的标志。调用它将--output_wrapper "(function() {%output%})();"在编译时将您的代码包装在匿名函数中。

Closure Compiler 用户经常发现在编译时进行这种包装比在原始源代码中编写匿名函数包装更容易和简单。

于 2013-08-26T17:31:30.300 回答