问题描述
我的webapp基于一个通用脚本,我在其中定义了常用函数和全局变量以及处理这些函数的动态加载脚本。到目前为止,我发现导出全局变量的唯一方法是用 window [myGlobalVar]
替换任何出现但我发现它非常难看。还有更好的方法吗?
My webapp is based on a common script where I define the common functions and a global variable and dynamically loaded scripts that process those. So far, the only way I found to export the global variable is to replace any occurrence by window["myGlobalVar"]
but I find it very ugly. Is there a better way to do?
这是一个例子
// commonscript.js before compilation
function incrementVariable() {window["myGlobalVar"]++;}
window["incrementVariable"] = incrementVariable;
window["myGlobalVar"] = 0;
和另一个脚本
alert(myGlobalVar); // <= alerts 0
incrementVariable();
alert(myGlobalVar); // <= alerts 1
我正在寻找直接使用的方法 myGlobalVar 因为它会更优雅。但是,我需要将 window [myGlobalVar]
设置为指针而不是对象的副本,我不知道如何在简单类型上执行此操作。
I am looking for a way to use directly myGlobalVar
in both files because it would be more elegant. However, I would need to set window["myGlobalVar"]
to a pointer and not a copy of the object and I am not sure how to do that on simple types.
有可能吗?是否只在对象
中封装 myGlobalVar
唯一的其他方式?
Is it possible? Is encapsulating myGlobalVar
in an Object
the only other way?
非常感谢您的灯光。
推荐答案
新答案
Closure-compiler支持 @nocollapse
注释,该注释可防止属性折叠为全局变量。这允许属性在导出时是可变的。
New Answer
Closure-compiler supports an @nocollapse
annotation which prevents a property from being collapsed to a global variable. This allows the property to be mutable when exported.
@nocollapse
不会阻止重命名 - 你仍然需要导出实现这一目标的属性。
@nocollapse
does not block renaming - you still need to export a property to accomplish that.
@nocollapse
目前仅在从源代码编译时受支持。它将包含在下一个版本中 - 即版本 AFTER v20150315版本。
@nocollapse
is currently only supported when compiling from source. It will be included in the next release - that is versions AFTER the v20150315 release.
@expose
现已弃用。编译器会警告任何使用 @expose
@expose
is now deprecated. The compiler will warn about any usage of @expose
有一个新的,但到目前为止没有证件,annoatation:@expose。此单个注释将导出属性并防止其从构造函数折叠。它听起来非常适合您的情况 - 但它需要您的变量作为对象的属性。
There is a new, but so far undocumented, annoatation: @expose. This single annotation will both export a property and prevent it from being collapsed off a constructor. It sounds like the perfect fit for your situation - but it will require your variable to be a property on an object.
但是,要小心使用。任何具有@expose的属性都不会被重命名,也不会被删除为死代码。这使得javascript库编写者使用它特别成问题。
However, use with care. Any properties which have @expose will not be renamed and will not be removed as dead code. This makes it especially problematic for use by javascript library writers.
这篇关于Javascript Closure编译器 - 导出全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!