Confused by Javascript's variable scope

前端 未结 2 663
臣服心动
臣服心动 2021-01-27 07:09

I\'m finding myself by Javascript\'s variable scope, could someone explain to me why the first example doesn\'t work but the second does?

function test() {
  ret         


        
2条回答
  •  时光说笑
    2021-01-27 07:38

    Explained in comments:

    function test() {
      return typeof(the_variable) !== 'undefined' && the_variable;
    }
    
    // The variable in this function is scoped to the anonymous function.
    // It doesn't exist outside that function, so `test` cannot see it
    (function () {
       var the_variable = "doesn't work";
       console.log(test());
    }());
    
    // This variable exists in a scope that wraps the `test` function, so it can see it.
    var the_variable = "does work";
    console.log(test());
    

提交回复
热议问题