Demonstrates deleting all global variables for a StackOverflow answer. http://stackoverflow.com/questions/16915009/generic-method-in-javascript-to-destroy-all-global-variables
/**
* 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 + " ]");
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.