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()
.)
You can help the compiler optimize these by writing wrappers around the builtin functions:
Produces:
This can also be useful when you wrap commonly used things like
document.createElement()
for obfuscation and to an extent minification (when uncompressed).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:
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