【问题标题】:Closure compiler doesn't virtualize prototype functions contained inside anonymous wrapper闭包编译器不会虚拟化匿名包装器中包含的原型函数
【发布时间】:2011-12-13 11:54:54
【问题描述】:

我正在尝试使用 Google Closure Compiler 的高级模式,似乎只有在未包装在匿名包装器中时才内联简单的小函数。寻找解释/解决方案或提示我做错了什么。

这是我的测试:

function Test() {
}
Test.prototype.div = function (index) {
    return Math.floor(index / 32);
};
Test.prototype['test'] = function (index) {
    return this.div(index);
};
window['Test'] = Test;

这导致了这个小脚本,其中div 函数被内联

function a() { } 
a.prototype.test = function(b) { return Math.floor(b / 32) }; 
window.Test = a;

接下来,测试包装如下:

(function () { // <-- added
    function Test() {
    }

    Test.prototype.div = function (index) {
        return Math.floor(index / 32);
    };

    Test.prototype['test'] = function (index) {
        return this.div(index);
    };

    window['Test'] = Test;
}()); // <-- added

div 函数没有内联

(function() { 
    function a() { } 
    a.prototype.a = function(a) { return Math.floor(a / 32) }; 
    a.prototype.test = function(a) { return this.a(a) }; 
    window.Test = a
})();

是否有一些我不知道的副作用阻止了这里的内联?

更新 1:我正在使用 online compiler 并勾选了高级模式 + 漂亮打印。

更新2:发现可以使用命令行参数--output_wrapper作为变通方法,--output_wrapper "(function() {%output%})();"

【问题讨论】:

  • 这不是内联,而是原型虚拟化。这是一个已知问题:code.google.com/p/closure-compiler/issues/…
  • 感谢您更正术语;在问题报告中也有有趣的阅读(几乎与我提出的示例完全相同)。如果您将您的评论作为答案,我会接受它
  • 仅供参考,您说的是内联。 Stephen 正在谈论“去虚拟化”,这是编译器启用内联和其他优化的一种方式。编译器能够在 ADVANCED 模式下内联方法而无需先进行去虚拟化,但相关代码非常保守。
  • @John,我认为在较新版本的编译器中支持闭包内的内联,但如果它是原型则不支持,在内联之前必须先将其虚拟化为全局函数,因为内联确实原型函数不会发生。

标签: javascript google-closure-compiler


【解决方案1】:

这不是内联,而是原型虚拟化

这是一个已知问题:Closure compiler issue

【讨论】:

  • 正如我刚刚了解到的那样; 可视化应该是虚拟化 :-)
【解决方案2】:

不,除了在编译器中执行内联的逻辑外,没有什么能阻止内联。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    相关资源
    最近更新 更多