Javascript global variable scope issue

前端 未结 4 982
说谎
说谎 2021-01-12 21:39

I am running into a strange scope issue with Javascript (see JSFiddle):

var someGlobal = 3;

function someF() {
    // undefined issue
    alert(someGlobal);         


        
4条回答
  •  感动是毒
    2021-01-12 22:05

    someF creates a new (locally scoped) variable called someGlobal (which masks the global someGlobal) and assigns a value to it. It doesn't touch the global someGlobal (although cannot access it because there is another variable with the same name in scope).

    var statements are hoisted, so someGlobal is masked for all of someF (not just after the var statement). The value of the local someGlobal is undefined until a value is assigned to it.

    someF2 access the original (untouched) global someGlobal.

提交回复
热议问题