JavaScript scope in a try block

后端 未结 6 1875
礼貌的吻别
礼貌的吻别 2020-12-30 20:37

Say I\'m trying to execute this JavaScript snippet. Assume the undeclared vars and methods are declared elsewhere, above, and that something and something

6条回答
  •  臣服心动
    2020-12-30 20:54

    Due to javascript "hoisting" (google it), your variable declaration code gets translated as:

    function yourFunction() {
      var magicVar;
      try {
          if(something) {
              magicVar = -1;
          }
    
          if(somethingElse) {
              magicFunction(magicVar);
          }
      } catch(e) {
          doSomethingWithError(e);
      }
    
    } //end of your function
    

    "Hoisting" moves all variables declarations to the top of the function. So magicVar is available everywhere in the function, but it's undefined until you give it a value.

    Your variable has function scope.

提交回复
热议问题