A question about var

var a = "global scope";
function b () {
var a =" local scope";
eval ("console.log (a Magi 1)"); / / local scope
(new Function (", "console.log (a Magne 2)")) (); / / global scope
}
b ();
what is wrong with this code? : ReferenceError: an is not defined

the global variable a will not report an error without var declaration:
a = "global scope";
function b () {
var a =" local scope";
eval ("console.log (console.log)"); / / local scope
(new Function (", "console.log (AM2)")) (); / / global scope
}
b ();
print:
local scope 1
global scope 2

Dec.24,2021

quote the interpretation of MDN

functions generated using the Function constructor do not create closures in the context in which they were created; they are typically created in the global scope. When running these functions, they can only access their own local and global variables, not the scope of the context generated by the call to the Function constructor. This is different from using eval with function expression code.

even so, your code can be executed in the browser environment.
you should execute the code in the node environment, and the variables declared with var outside the function are not global variables

.

the problem cannot be repeated

Menu