The problem of modifying global variables inside JavaScript functions "a question of a face"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.