问题
The following code:
(function() {
var hello = function(name) {
alert('Hello, ' + name);
}
hello('New user');
})();
with ADVANCED_OPTIMIZATIONS
is compiled to:
alert("Hello, New user");
But this code:
(function() {
var hello = function(name) {
alert('Hello, ' + name);
}
hello.a = 5;
hello('New user');
})();
is compiled to:
function a(b){alert("Hello, "+b)}a.a=5;a("New user");
Why it cannot ignore the hello.a = 5
?
(It cannot be used outside the context, there is no eval
, no []
and no new Function()
.)
回答1:
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);
}
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.
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
回答2:
You can help the compiler optimize these by writing wrappers around the builtin functions:
function myalert(name){alert('Hello, ' + name)}
(function() {
var hello = function(name) {
myalert(name);
}
hello.a = 5;
hello('New user');
})();
Produces:
alert("Hello, New user");
This can also be useful when you wrap commonly used things like document.createElement()
for obfuscation and to an extent minification (when uncompressed).
来源:https://stackoverflow.com/questions/16546577/closurecompiler-removing-dead-code-with-advanced-optimizations