Let's say that I want to get a list of all the variables in the window
that are user-defined. In other words, they're not properties or objects that the browser has created or defined in ECMAScript.
For example, let's say there's this script on a page:
<script>
window.__$DEBUG = true;
var Analytics = function() {};
</script>
I would like to be able to loop through window
and get a list containing __$DEBUG
and its value, and Analytics
and its value:
var nonNatives = (function nonNative(scope) {
var result = {};
for (var child in scope) {
if (!isNative(child)) {
result[child] = scope[child];
}
}
return result;
})(window);
Can this be done?
I've previously done this by creating a single function (loaded before any other JS) which remembers the current keys of window
(i.e. the built-in properties) and which when called again displays the differences.
If the purpose is just to detect accidentally global variables, the aforementioned function can be an anonymous IIFE (such that it doesn't itself pollute the global scope) which contains the current list in scope, which then periodically calls another enclosed function (with setTimeout
) to compare the list, and update it for next time, e.g:
(function(scope) {
var keys = Object.keys(scope);
var map = {};
for (var i = 0, n = keys.length; i < n; ++i) {
map[keys[i]] = 1;
}
(function update() {
var current = Object.keys(scope);
// compare lists and print the differences
for (i = 0, n = current.length; i < n; ++i) {
var name = current[i];
if (!(name in map)) {
console.log(name + ' = ' + scope[name]);
map[name] = 1;
}
}
// loop
setTimeout(update, 1000);
})();
})(window);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With