Possible Duplicate:
Fetching all (javascript) global variables in a page
My application is using global variables in javascript. Is there a way to find how many of them are there?
Thanks Om
Possible Duplicate:
Fetching all (javascript) global variables in a page
My application is using global variables in javascript. Is there a way to find how many of them are there?
Thanks Om
I made one.
var GlobalTester = (function(){
var fields = {};
var before = function(w){
for(var field in w){
fields[field] = true;
};
};
var after = function(w){
for(var field in w){
if(!fields[field]){
console.log(field + " has been added");
}
};
};
return {before: before, after:after};
}());
GlobalTester.before(window);
// Run your code here
window.blar = "sdfg";
GlobalTester.after(window);
This will output blar has been added
in the console
Try this in your browser developer window (F12):
Object.keys(window).length
Iterate through the window element like this:
for(var globe in window){
console.log(globe);
}
Using a linter would warn you when globals are introduced. You could also compare items of window
before and after your code runs.
Inspect the window object, but you will need to know all of the global variable names before you do this, here is an example:
var myGlobalVars = {"global1":0, "global2":0};
function countGlobals() {
var count = 0;
for (myGlobalVar in myGlobalVars) {
if (myGlobalVar in window) {
count++;
}
}
return count;
}
countGlobals();