Why does Google Closure Compiler adds variable to the global namespace when the original namespace was empty?

只愿长相守 提交于 2019-12-22 09:12:07

问题


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?


回答1:


The compiler expects that it's given all relevant JavaScript so that it doesn't need to worry about clashes with other scripts. Therefore it assumes that it can unwrap the "unnecessary" anonymous function.

From the 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.



来源:https://stackoverflow.com/questions/18449503/why-does-google-closure-compiler-adds-variable-to-the-global-namespace-when-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!