Javascript模块模式,Prototype和Google Closure
我无法通过Google Closure Compiler获得此代码结构以避免混淆。以下是一些示例代码:
I am having trouble getting this code structure to survive obfuscation with the Google Closure Compiler. Here's some sample code:
var MyModule = (function()
{
function myModule()
{
// Constructor
}
function moduleFoo(url)
{
// Method
}
function moduleBar()
{
// Method
}
myModule.prototype = {
constructor: myModule,
foo: moduleFoo,
bar: moduleBar
};
return myModule;
})();
在我的代码中,我需要能够编写如下内容:
Elsewhere in my code I need be able to write things like the following:
var myMod = new MyModule();
myMod.foo();
myMod.bar();
然而,编译器正在重命名所有内容(如预期的那样)。如何在混淆后制作我在代码中其他地方定义的原型?我已尝试导出如下:
However the compiler is renaming everything (as expected). How can I make the prototype that I have defined available elsewhere in my code after obfuscation? I have tried exporting as follows:
// In place of the prototype object above
myModule.prototype['constructor'] = myModule;
myModule.prototype['foo'] = moduleFoo;
myModule.prototype['bar'] = moduleBar;
window['myModule'] = myModule;
但是当调用原型方法或执行相应的闭包时,事情似乎都会崩溃。
But things seem to break down either when the prototype methods are called or when their corresponding closures are executed.
感谢任何帮助。
这种确切的模式不会使用ADVANCED_OPTIMIZATIONS与Closure编译器配合良好。相反,您需要稍微重构您的代码:
This exact pattern does not work well with Closure-compiler using ADVANCED_OPTIMIZATIONS. Instead, you will need to slightly refactor your code:
/** @constructor */
function MyModule()
{
// Constructor
}
(function() {
function moduleFoo(url)
{
// Problem using "this" keyword. Will require @this annotation.
}
MyModule.prototype = {
foo: moduleFoo
};
MyModule.prototype.bar = function() {
// "this" keyword works fine.
};
})();
或者喜欢:
/** @const */
var MyNamespace = {};
(function() {
/** @constructor */
MyNamespace.MyModule = function() {};
MyNamespace.MyModule.prototype = {
constructor: function() {},
foo: function(url) {},
bar: function() {}
};
})();
使用上述任何一种方法,您的出口都可以正常运作。
With either of the above methods your exports should work correctly.
注意:第二个选项仅适用于从最新源构建的编译器,因为它涉及上周刚刚修复的错误。