JavaScript scope in a try block

后端 未结 6 1839
礼貌的吻别
礼貌的吻别 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:47

    Javascript has function scope. That means that magicvar will exist from the beginning of the function it's declared in all the way to the end of that function, even if that statement doesn't ever execute. This is called variable hoisting. The same thing happens with functions declarations, which in turn is called function hoisting.

    If the variable is declared in global scope, it will be visible to everything. This is part of the reason why global variables are considered evil in Javascript.

    Your example will pass undefined into magicFunction if something is false, because magicVar hasn't been assigned to anything.

    While this is technically valid Javascript, it's generally considered bad style and will not pass style checkers like jsLint. Extremely unintuitive Javascript like this will execute without any error

    alert(a); //alerts "undefined"
    var a;
    

    POP QUIZ: What does the following code do?

    (function() {
      x = 2;
      var x;
      alert(x);
    })();
    alert(x);
    

提交回复
热议问题