problems with modifying global variables inside JavaScript functions Share | Today 10:44 Brahma Lotus | Browse 23 times JavaScript programming language functions Modify tags
The code is as follows, why add function A () {}; This function cannot change the value of global variable a?
var a = 1;
Function B () {
A = 2;
Console.log (a);
There is a function, a does not change, no function, a change 2
function A () {};
}
b ();//Output 2
Console.log (a);//Output 1
Today 11:07The questioner is adopted by
Because
A. A function in JavaScript is a value, and a numeric object string is a value
B. JavaScript will pre-parse the entire code, one of which is to pre-bind function functionname () {} In this form to its scope
So, your B function body is equivalent to
Function B ()
{
function A () {}
A = 2
Console.log (a)
}
So it doesn't change the global value
Ask:Today 11:44
Thanks for the reply, the function declaration in B in advance I know some, but a is a great inspiration to me. Do you mean that the variable a=2 actually re-assigns the function A () to a numeric variable? Then the function a () can be regarded as a local variable, a=2 although there is no previous add Var, but also just to a () This local variable is re-assigned, but a is still a local variable, only with the function outside the global variable a=1 name, so understand it?
Chase Answer:Today 11:52
' Variable a=2 actually re-assigns function a () to a number variable? '
That's right
' But a is still a local variable, just the same name as the global variable a=1 outside the function '
That's right
Ask:Today 12:47
OK, thanks a lot!
The problem of modifying global variables inside JavaScript functions "a question of a face"