Karl
Karl

Reputation: 1864

Why is Closure Compiler generating different syntax?

Why does the Closure Compiler generate different code (using advance option) for the following two functions:

  var function1 = function() {
        return 1 * Math.random();
  };

  window['function1'] = function1;  // export function1

  var function2 = function() {
        return function1() + 1;
  };

  window['function2'] = function2;  // export function2

This is the code generated:

  function a() {
        return 1 * Math.random();
  }

  window.function1 = a;

  window.function2 = function() {
        return a() + 1;  // call to a() fails in a more complex example
  };

Notice that function1 has been renamed to a and a is assigned to the global varible function1. With function2 there is no other variable name associated with it. Why?

The reason why I ask is, in the case with my code, the call to function1 from function2 fails because the renamed function1 is not seen as a function call in function2 but rather the Javascript interpreter thinks that a() is a number.

Any insight is appreciated. TIA.

Upvotes: 1

Views: 100

Answers (2)

John
John

Reputation: 5468

If "a" is a number, most likely it is getting overwritten by something else. If you aren't using multiple modules, try using the output wrapper option to isolate the globals (There are other options to isolate globals if you are using multiple modules). Often defining a setter on "windows.a" and setting a break point there will let you know how this overwrite is happening.

Upvotes: 2

Chad Killingsworth
Chad Killingsworth

Reputation: 14411

Using ADVANCED_OPTIMIZATIONS, Closure Compiler will remove unused code. Since the only use of function2 was in the export, the assignment was made directly to the exported name (rather than first to a variable). function1 was both exported and used by function2 so the compiler left the initial named function as it was referenced twice.

As for the failure, we'd need to see your actual code to explain what's happening.

Upvotes: 2

Related Questions