Delete Globals

Demonstrates deleting all global variables for a StackOverflow answer. http://stackoverflow.com/questions/16915009/generic-method-in-javascript-to-destroy-all-global-variables

by ChadSchouggins

HTML

<div id="log"></div>

CSS

div#id {
    border: 1px solid #000000;
    min-height: 8px;
    min-width: 8pc;
}

JavaScript

/**
 * Simply logs messages to the results panel.
 */
function log(message) {
    var logElement, logEntryElement, messageElement;

    logElement = document.getElementById("log");
    logEntryElement = document.createElement("div");
    messageElement = document.createTextNode(message);

    logEntryElement.appendChild(messageElement);
    logElement.appendChild(logEntryElement);
}

/**
 * To be called first to take note of any default globals we don't want to (and 
 * probalbly can't) delete.
 */
function loadInitialGlobals() {
    var x;

    // We'll attach this to the deleteAllGlobals function so its persisted, but not a global.
    // It's also globally accessable so globals can be protected from deletion.
    deleteAllGlobals.ignore = deleteAllGlobals.ignore || [];

    for (x in window) {
        ////////////////////////
        // See all the globals
        // Uncomment below
        ////////////////////////

        // log(x);

        deleteAllGlobals.ignore[x] = true;
    }
}

/**
 * Deletes all global variables.
 * Ignores any globals in the initialGlobals array.
 */
function deleteAllGlobals() {
    var x, e;

    log("Deleting all globals...");

    for (x in window) {
        if (!deleteAllGlobals.ignore[x]) {
            log("- " + x);
            delete window[x];
        }
    }

    log("...Done");
    log(" ");
}


function oops() {
    someSupposedlyLocalVariable = 5;
}

// Fist, we take note of all inital globals (we don't want to (try to) delete them later).
loadInitialGlobals();

// Lets add some globals
someGlobalVariable = "global";
someOtherGlobalVariable = "global";

oops();

protectedGlobal = "protected";
deleteAllGlobals.ignore.protectedGlobal = true;

// Now, lets delete the globals we just made.
deleteAllGlobals();

// And verify the results
log("[ " + typeof someGlobalVariable + " ]");
log("[ " + typeof someOtherGlobalVariable + " ]");
log("[ " + typeof someSupposedlyLocalVariable + " ]");
log("[ " + protectedGlobal + " ]");