Javascript global variable scope issue

前端 未结 4 946
说谎
说谎 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();
    

提交回复
热议问题