谷歌闭包编译器中的高级编译

时间:2014-12-02 11:22:30

标签: javascript google-closure-compiler

我有这个代码,我正在尝试使用闭包编译器来优化代码。

var HrevertGraph = HrevertGraph || {};
HrevertGraph.CircularProgress = (function(){
  function Progress(){
    //Properties
  }

  Progress.prototype.getCenter = function() {
   //method
  }

  //and other methods
  return Progress;

})();
window["HrevertGraph.CircularProgress"] = HrevertGraph.CircularProgress;

我在高级选项模式下编译了这个,问题是编译后的代码没有显示构造函数Progress及其原型方法。 在这种情况下我该怎么做?

1 个答案:

答案 0 :(得分:2)

如果您不希望闭包编译器更改原型成员,您可以这样做:

Progress.prototype['getCenter']=function....

但是你必须在编译代码中使用括号表示法来调用这个函数。

导出构造函数时,您可以执行以下操作:

window["HrevertGraph"] = {};
window["HrevertGraph"]["CircularProgress"] = HrevertGraph.CircularProgress;

<强> [UPDATE]

这是一个可以在运行未编译代码的页面控制台中运行的函数。控制台中的输出是要编译的代码中的导出,复制和粘贴,它将导出构造函数和原型。例如,特定成员(使用this.something = ...定义在Progress中的成员)没有简单的脚本来生成导出。最好在Progress构造函数中使用this['something']=this.something之类的东西来处理它们。

function exportConstructor(objPath){
  var i = -1,len = objPath.length,ret=[]
  ,exPath='window',clPath='window',
          o,thing;
  while(++i<len){
    exPath=exPath+'["'+objPath[i]+'"]';
    clPath=clPath+'.'+objPath[i];
    ret.push(exPath);
    ret.push("=");
    ret.push(clPath);
    ret.push(";\n");
  }
  var i = 0,o=window[objPath[i]];
  while(++i<len){
    o=o[objPath[i]];
  }
  o=o.prototype;
  exPath=exPath+'["prototype"]';
  clPath=clPath+'.prototype';
  for(thing in o){
      if(Object.hasOwnProperty.call(o,thing)){
      exPath=exPath+'["'+thing+'"]';
      clPath=clPath+'.'+thing;
      ret.push(exPath);
      ret.push("=");
      ret.push(clPath);
      ret.push(";\n");
    }
  }
  return ret.join("");
}
console.log(exportConstructor(['HrevertGraph','CircularProgress']));
相关问题