/ Published in: JavaScript
To safely declare variables. Well, actually use this to tell before the fact whether you would clobber a var with a name. It won't be declared, and you'll receive a nice, breathy error.
It's more of a diagnostic tool, I suppose.
Expand |
Embed | Plain Text
function safelyDeclare(varName, varVal) { varName = (varName.indexOf("window.") != -1) ? varName = varName.replace("window.", "") : varName; if ( window[varName] || window.varName ) { throw new Error("Variable '"+varName+"' is an existing global variable. You may find clobbering it to be an undesirable outcome!"); } else { eval(varName+' = '+varVal+';'); } } window.onload = 3; safelyDeclare('window.onload', function() { console.log("My backpack's got jets."); }); // error window.onload(); boba = 3; safelyDeclare('boba_fett', function() { console.log("My backpack's got jets."); }); //no error since "boba_fett" is not in the [window] object boba_fett();
You need to login to post a comment.
