Posted By

nerdfiles on 03/05/10


Tagged

javascript js global vars


Versions (?)

SafelyDeclare


 / 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.

  1. function safelyDeclare(varName, varVal) {
  2. varName = (varName.indexOf("window.") != -1)
  3. ? varName = varName.replace("window.", "")
  4. : varName;
  5.  
  6. if ( window[varName] || window.varName ) {
  7. throw new Error("Variable '"+varName+"' is an existing global variable. You may find clobbering it to be an undesirable outcome!");
  8. } else {
  9. eval(varName+' = '+varVal+';');
  10. }
  11. }
  12.  
  13. window.onload = 3;
  14.  
  15. safelyDeclare('window.onload', function() { console.log("My backpack's got jets."); }); // error
  16.  
  17. window.onload();
  18.  
  19.  
  20. boba = 3;
  21.  
  22. safelyDeclare('boba_fett', function() { console.log("My backpack's got jets."); }); //no error since "boba_fett" is not in the [window] object
  23.  
  24. boba_fett();

Report this snippet  

You need to login to post a comment.