How to solve the problem of js scope?

    var a= 1;
    function fn1(){
        alert(a);
        a = 2;
    }
    fn1();
    alert(a);

output 1 first, and then output 2

I would like to ask the browser about the process of performing this, and ask for advice


when executing the alert (a) inside fn1 (), if there is no variable an inside fn1, it will look for it in the global scope, where an is 1; Then an is assigned to 2, so the following alert (a) is 2


var a = 1 , which means that an is defined as a global variable. When you fn1 (), the internal, alert (a) of the fn1 function is not defined as a, so it will look for an in the global scope, so the first time is alert (1), and then your an is changed to 2 (the second an is also global). The an in the bottom alert (a) is 2


the execution order has already been answered, so I won't repeat it any more.

in fact, if you want to know the order of execution, you can take a look at the breakpoint, which is more convenient and clear.


your code is equivalent to

var a;
function fn1(){
    alert(a);
    a = 2;
}
a = 1;
fn1();
alert(a);

function fn1 increases, and then an assignment, the first 1, is printed in fn1, an equals 2 after printing, and then prints 2.

Menu