Why can you access the variables defined in the function (non-closure)?

the code is as follows:

    (function test() {
      var a = 5;
      alert(typeof a);
      alert(typeof b);
    })()
    alert(typeof a);
    alert(typeof b);

output result:
number number undefined number

Why can you access b outside the function here

Sep.04,2021

alert(typeof a);
alert(typeof b);

this a, b is not the above a, b
even if the function is not executed immediately

alert(typeof a);
alert(typeof b);

also outputs, typeof is a safe way to output undeclared variables (just remember, typeof executes normally for undeclared variables)
for reasons I guess he called alert (typeof window.b);

The

variable b is declared outside the self-executing function, both inside and outside the function can access the externally declared variables, while the self-executing function can not access the variables inside.


according to your target code, number undefined must declare


outside the self-execution function according to your output variable b. When the global variable b is a number type test, you can only write this content in the local code and look at the print effect. Do not print directly in the browser so that your browser, such as If there is a definition, b will also be entered into the corresponding type

Menu