Can you clarify this JavaScript variable hoisting behavior?

前端 未结 3 1658
-上瘾入骨i
-上瘾入骨i 2021-01-25 14:22

Case1:

var text = \'outside\';
function logIt(){
    console.log(text);
    text =\'inside\';
}
logIt(); //prints outside. why?

I thought the

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-25 15:08

    Because of hoisting the inner variable text is moved to the beginning of the function. But only it's name portion:

    var text = 'outside';
    function logIt(){
        var text;
        console.log(text);
        text ='inside';
    }
    logIt(); //prints undefined
    

    Case 1 logs "outside", because text is a variable in the surrounding scope of logIt and hence accessible within logIt. You reassign text lexically after the console.log call. So this reassingment isn't considered.

提交回复
热议问题