Closing compiler / uglifyjs - is this function name not abbreviated?

If I run this piece of code through the closure compiler or uglifyjs, this.init is not shortened. Can someone tell me why this is so?

function test() { var v = "abc"; this.init = function() { alert('var = ' + v + ' and func = ' + f()); f2(); } function f() { return 'def'; } function f2() { v = "ghi"; alert('blabla'); alert('filler'); } } test(); 

uglifyjs turns this into:

 function test(){function c(){a="ghi",alert("blabla"),alert("filler")}function b(){return"def"}var a="abc";this.init=function(){alert("var = "+a+" and func = "+b()),c()}}test() 

Decorated that is:

 function test() { function c() { a = "ghi", alert("blabla"), alert("filler") } function b() { return "def" } var a = "abc"; this.init = function () { alert("var = " + a + " and func = " + b()), c() } } test() 

So why has this.init () not changed for a shorter name?

In addition, what exactly is the difference:

  function init() {..} 

and

  this.init = function() { .. } 

Thanks Wesley

+4
source share
1 answer

init not shortened for the same reason test not shortened ... because it is part of the public API of your code.

When you call var t = new test() you will create an object that looks like this:

 { init: function() { ... }, prototype: test } 

and you can call t.init() . If the compiler did not respect those variables that are accessible from the global scope, you will need to embed all the JavaScript code in a single file before you minimize it. Otherwise, every time you minimize test.js , the name of the public function test would change. So this code:

 <script type="text/javascript" src="js/test.min.js"></script> <script type="text/javascript"> var t = new test(); t.init(); </script> 

will be broken (because test will possibly be changed from a to minifier and init to another letter.)

As for the second part of your question, when you execute this.init = function , you set an attribute for an undefined object (this can be anything, since this set during a conversation in JavaScript and you declare it inside the test function). When you write function init(){} , you write a function declaration that will be raised at the top of the enclosing area (which means you can call it inside the area in which it is defined before you define it.) However, it will not be available outside of test .

+5
source

All Articles