Closure编译器:重命名对象键但仍能在其他脚本中使用原始键

时间:2014-04-23 11:45:39

标签: javascript google-closure-compiler

此代码将重命名对象键,并仍然可以使用原始键

调用函数
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// ==/ClosureCompiler==

var myClass = function() {
  this["myFunc"] = this.myFunc;
  this["myFunc2"] = this.myFunc2;
};
window["myClass"] = myClass;

myClass.prototype = {
  myFunc: function() { alert("myFunc"); },
  myFunc2: function() { alert("myFunc2"); }
};

编译成

function a(){
    this.myFunc=this.a;
    this.myFunc2=this.b
}
window.myClass=a;
a.prototype={
    a:function(){alert("myFunc")},
    b:function(){alert("myFunc2")}
};

(new myClass()).myFunc()(new a()).a()都可以使用

但是,此方法需要声明myFunc1myFunc2 ... myFuncN太多时间

其他方式是否可以实现同样的目标?

我希望使用闭包编译器将所有myFunc重命名为a(类似这样)

在同一个脚本中,调用myClass.myFunc()将编译为a.b()

但我仍然可以在其他脚本中调用window.myClass.myFunc()

非常感谢。

2 个答案:

答案 0 :(得分:0)

(new myClass()).myFunc()应该有效:)

无论如何,你也可以这样导出你的方法:

// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level ADVANCED_OPTIMIZATIONS
// ==/ClosureCompiler==

var myClass = function() {
   //don't declare your exports here
};

myClass.prototype["myFunc"] = function() { alert("myFunc"); };
myClass.prototype["myFunc2"] = function() { alert("myFunc2"); };

window['myClass'] = myClass;

这不容易出错,因为你不必记得"初始化"所有方法名称 它汇编为:

function a() {
}
a.prototype.myFunc = function() {
  alert("myFunc");
};
a.prototype.myFunc2 = function() {
  alert("myFunc2");
};
window.myClass = a;

答案 1 :(得分:0)

  

我想使用window.myClass.myFunc

在其他脚本上访问它们

这表示您希望以window的方式设置属性,即new的结果,例如

window.myClass = (function () { // make a closure with IIFE
    function a() {
        // if all you want is on the prototype, nothing to do here
    }
    a.prototype = { // set prototype
        myFunc: function () {alert("myFunc")},
        myFunc2: function () {alert("myFunc2")}
    };
    return new a(); // construct, return out of IIFE
}()); // Invoke IIFE

现在,window.myClass是带有原型的构造对象,您可以使用

window.myClass.myFunc(); // alerts "myFunc"

如果原型设计/继承对您不重要,您可以简单地执行

window.myClass = { // set directly
    myFunc: function () {alert("myFunc")},
    myFunc2: function () {alert("myFunc2")}
};

如果原型设计/继承对您很重要,但您不需要构建并且可以采用现代浏览器,

window.myClass = Object.create(
    { // prototype
        myFunc: function () {alert("myFunc")},
        myFunc2: function () {alert("myFunc2")}
    }
);