Javascript Odd Scoping Behavior

后端 未结 3 667
Happy的楠姐
Happy的楠姐 2021-01-22 07:21

I\'ve been going through Javascript function scope and have run into this:

var scope = \"global\";

function f(){
    console.log(scope);

    var scope = \"loca         


        
3条回答
  •  轮回少年
    2021-01-22 08:01

    Two-pass parsing. The code will be treated as if it was

    function f() {
       var scope;  // var created, but no value assigned. this overrides the earlier global
       console.log(scope);
       scope = 'local';
       console.log(scope);
    }
    

    The var's CREATION will be executed as if it was the very first bit of code executed in the function. But the actual assignment operation won't occur until where it normally would.

提交回复
热议问题