As we all know, when we use var
to declare a variable in the file level, it is accessible by all other JS files that are loaded in the same HTML page. I am now trying to transform them into ES6. Therefore, I would like to eliminate all those variable sharing.
There are a lot of people suggest to use code like Object.keys( window );
in console to find all of them. However, there are a lot more variables that weren't defined in my scripts and I would like to do this analysis statically.
NOTE: This can't be done by relying on linting tools to report "undeclared identifier". For example, below are the files for adding new members to the same global object(variable) called g
. The js load order is file a
and then file b
. As you can see, g
is a global variable. However, linting tools don't say which global variable is shared by more than one JS file.
File a
var g;
if(typeof g === 'undefined')
g = {};
g.something = 1;
File b
var g;
if(typeof g === 'undefined')
g = {};
g.hey = 2;
console.log(g.something); // this works
NOTE: This can't be done by traversing the window
object. First, this is not done statically. Second, there are a lot of predefined objects by the browsers which are not inherited - We can't know whether they are used by any user-written JS file.