3

我的 webapp 基于一个通用脚本,在该脚本中我定义了通用函数和一个全局变量,并动态加载了处理这些函数的脚本。到目前为止,我发现导出全局变量的唯一方法是将任何出现替换为,window["myGlobalVar"]但我觉得它非常难看。有更好的方法吗?

这是一个插图

// 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"]为指针而不是对象的副本,并且我不确定如何在简单类型上执行此操作。

可能吗?封装myGlobalVarObject唯一的另一种方式吗?

非常感谢你的灯。

4

2 回答 2

8

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 does not block renaming - you still need to export a property to accomplish that.

@nocollapse is currently only supported when compiling from source. It will be included in the next release - that is versions AFTER the v20150315 release.

Old Answer

@expose is now deprecated. The compiler will warn about any usage of @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.

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.

于 2012-04-30T13:01:23.850 回答
0

如果您想要一个不被重命名的变量,只需创建一个名为 example 的文件,props.txt其中包含以下内容:

myGlobalVar:myGlobalVar

然后在编译代码时,添加命令行参数:--property_map_input_file props.txt

您的变量不会被重命名,并且只要它没有被优化掉,它就可用于所有脚本。此外,如果您根本不声明它(所以您省略var myGlobalVar),它不会被重命名或删除。

于 2012-05-03T18:34:40.263 回答