Javascript模块模式,Prototype和Google Closure [英] Javascript Module pattern, Prototype and Google Closure

查看:121
本文介绍了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.

注意:第二个选项仅适用于从最新源构建的编译器,因为它涉及上周刚刚修复的错误。

这篇关于Javascript模块模式,Prototype和Google Closure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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