Javascript global variable scope issue

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

    Here is an example of how to use both the local and global variable inside someF by using this.

    var someGlobal = 3;
    
    function someF() {
    
        // Displays 3
        alert(someGlobal);
        this.someGlobal = 5;
        someGlobal = 5;
        // Displays 5
        alert(this.someGlobal);
    }
    
    function someF2() {
        // Displays 5
        alert(someGlobal);
    }
    
    someF();
    someF2();
    

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-12 22:17

    someF2 displays 3 because it still is 3.

    In someF() you create a new variable that happens to have the same name as someGlobal. That does not do anything to the original someGlobal, it just creates a new variable locally to function someF that goes away when that function ends.

    So you have local variables (e.g. created inside someF with var) and global ones.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题