Javascript global variable scope issue

前端 未结 4 944
说谎
说谎 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:21

    Since you are declaring a local variable with the same name. So it assigns the value to the local variable. Just remove the var from var someGlobal in someF() and it should be fine.

    var someGlobal = 3;
    
    function someF() {
        // undefined issue
        alert(someGlobal);
        someGlobal = 5; // <-- orignially var someGlobal = 5
        // Displays 5
        alert(someGlobal);
    }
    
    function someF2() {
        // Should display 5 now
        alert(someGlobal);
    }
    
    someF();
    someF2();
    

提交回复
热议问题