Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 1.01 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. JavaScript scope in a try block
  2. try {
  3.     if(something) {
  4.         var magicVar = -1;
  5.     }
  6.  
  7.     if(somethingElse) {
  8.         magicFunction(magicVar);
  9.     }
  10. } catch(e) {
  11.     doSomethingWithError(e);
  12. }
  13.        
  14. alert(a); //alerts "undefined"
  15. var a;
  16.        
  17. (function() {
  18.   x = 2;
  19.   var x;
  20.   alert(x);
  21. })();
  22. alert(x);
  23.        
  24. function bar() {
  25.     var x = "outer";
  26.  
  27.     function foo() {
  28.         alert(x); // {undefined} Doesn't refer to the outerscope x
  29.         // Due the the var hoising next:        
  30.         x = 'inner';
  31.         var x;
  32.         alert(x); // inner
  33.  
  34.     }
  35.     foo();
  36. }
  37.  
  38. bar();​
  39.  
  40. bar();​
  41.        
  42. function foo() {
  43.     var x;
  44.     alert(x); // {undefined} Doesn't refer to the outerscope x
  45.     // Due the the var hoising next:        
  46.     x = 'inner';
  47.     alert(x); // inner
  48. }​
  49.        
  50. function yourFunction() {
  51.   var magicVar;
  52.   try {
  53.       if(something) {
  54.           magicVar = -1;
  55.       }
  56.  
  57.       if(somethingElse) {
  58.           magicFunction(magicVar);
  59.       }
  60.   } catch(e) {
  61.       doSomethingWithError(e);
  62.   }
  63.  
  64. } //end of your function