Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Enumerate non-native objects in given scope

Tags:

javascript

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?

like image 624
core Avatar asked May 24 '13 15:05

core


1 Answers

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);
like image 72
Alnitak Avatar answered Sep 20 '22 23:09

Alnitak