ClosureCompiler使用高级优化删除死代码 [英] ClosureCompiler removing dead code with advanced optimizations
问题描述
以下代码:
(function() {
var hello = function(name) {
alert('Hello, ' + name);
}
hello('New user');
})();
与 ADVANCED_OPTIMIZATIONS
p>
with ADVANCED_OPTIMIZATIONS
is compiled to:
alert("Hello, New user");
但此代码:
(function() {
var hello = function(name) {
alert('Hello, ' + name);
}
hello.a = 5;
hello('New user');
})();
编译为:
function a(b){alert("Hello, "+b)}a.a=5;a("New user");
为什么不能忽略 hello.a = 5
?
(不能在上下文之外使用,没有 eval
,否 []
并且没有 new Function()
。)
(It cannot be used outside the context, there is no eval
, no []
and no new Function()
.)
推荐答案
为了这个工作,编译器将需要确定没有人用一个函数替换了alert调用函数:
For this to work, the compiler would need to determine that no one had replaced "alert" with a function that looked at the the calling function:
alert = function() {
console.log(arguments.callee.caller.a);
}
但是alert是一个外部函数,因此无法确定什么它实际上。一般来说,javascript是如此mutable,以至于属性可以安全地从函数中移除的情况是如此罕见,不值得努力找到它们。
but "alert" is a external function so there is no way to determine what it actually does. Generally, javascript is so mutable that the cases where properties can be safely removed from functions are so rare it isn't worth the effort to find them.
一般来说, Closure编译器可以删除属性作弊。这里有一些讨论:
Generally, where the Closure Compiler can remove properties it is cheating. There is some discussion of this here:
https://github.com/google/closure-compiler/wiki/Understanding-Property-Removal
这篇关于ClosureCompiler使用高级优化删除死代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!