当原始命名空间为空时,为什么Google Closure Compiler会将变量添加到全局命名空间? [英] Why does Google Closure Compiler adds variable to the global namespace when the original namespace was empty?

查看:110
本文介绍了当原始命名空间为空时,为什么Google Closure Compiler会将变量添加到全局命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的脚本很好地包装在(function(){/.../})(/)/ code>中,以避免所有类型的名称污染。它是100%打字,没有警告。



我发现Google Closure编译器首先重新定义 i 和<全局命名空间中的code> j 感觉既不必要又危险,特别是因为我正在编译一个对命名空间没有干扰的脚本。 (编译后的脚本以 var i = null,j =!1; 开头,出于紧凑的原因,我相信)。



<我能想到一个工作是使用 - output_wrapper 来包装它,但我想不出谷歌会像这样污染命名空间的原因。



有没有?

解决方案

编译器希望给出它所有相关的JavaScript,因此无需担心与其他脚本的冲突。因此,它假定它可以打开不必要的匿名函数。



来自 FAQ


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



Closure编译器的高级优化模式假设可以添加新变量到了全局范围。



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



Closure编译器用户经常发现在编译时执行此包装更容易,更简单,而不是在原始源代码中编写匿名函数包装器。



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?

解决方案

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.

这篇关于当原始命名空间为空时,为什么Google Closure Compiler会将变量添加到全局命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆