Confused by Javascript's variable scope

前端 未结 2 667
臣服心动
臣服心动 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:34

    In Javascript, functions define scope. In your first example the_variable is outside of the scope of test. On the other hand, in the second example, the_variable is defined in the global scope and is available everywhere.

    EDIT

    Catch the_variable in a closure if you want it to be available to test.

    var foo = (function () {
       var the_variable = "does work";
       function test() {
           return typeof(the_variable) !== 'undefined' && the_variable;
       }
       return {test : test};
    }()); 
    console.log(foo.test());
    

    Output:

    does work

提交回复
热议问题