ClosureCompiler removing dead code with advanced o

2019-08-13 13:30发布

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().)

2条回答
趁早两清
2楼-- · 2019-08-13 13:55

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).

查看更多
做个烂人
3楼-- · 2019-08-13 14:11

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

查看更多
登录 后发表回答