Search code examples
gruntjsuglifyjsuglifyjs2

uglifyjs not obfuscating global variable


I'm using uglifyjs (via grunt) and am trying to get a global variable obfuscated, but it's not working. I'm using the 'toplevel' option with mangle.

Was wondering if anyone could answer why?

Bypassing grunt and using uglify directly, the command-line I'm using is:

uglifyjs js/a.js -c -m toplevel -o dist/scripts.js

The contents of a.js are:

foo = 5;

function bar() {
  var excellent = 10;

  var myvar = excellent*excellent;

  console.log('myvar = ' + myvar);
}

bar();

function useAGlobal() {
  console.log('foo = ' + foo);
}

useAGlobal();

and the uglified code is:

function o(){var o=10,n=o*o;console.log("myvar = "+n)}function n(){console.log("foo = "+foo)}foo=5,o(),n();

I can see the global functions bar() and useAGlobal() get obfuscated just fine, but why does the variable foo remain unchanged?

If I declare foo with the 'var' keyword as var foo = 5;, then it does get obfuscated. What am I missing here?

Thanks!


Solution

  • When you are doing foo = 5 without var it's considered an assignment compared to var foo = 5 which is a declaration. The reason why assignment variable name doesn't get obfuscated is that it is assuming that it is declared somewhere else outside of the current js in the global scope. In the browser, everything in the global scope is associated with window. So if you for example did location = 'http://www.google.com.au'; it would send your browser to google. If the location were to be obfuscated then the code wouldn't function correctly.