【发布时间】: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