Javascript scope chain generation Sequence

Source: Internet
Author: User

I have recently seen some ideas.

Javascript scope chain sometimes causes some strange problems. As a weak type of JavaScript, functions are also objects. The scope of variables is effective in the function body and has no block scope.

When JavaScript looks for variables or objects, it first looks for the internal context of the function body, and then the external context of the function.

While Javascript is in the lexical scope when constructing the scope, not when executing it. See the example of Abruzzi:

 
VaR STR = "Global"; function scopetest () {print (STR); var STR = "local"; print (STR) ;} scopetest ();

Result:

 
Undefined
Local

The parser does not call the external str of JavaScript. After the syntax analysis, it constructs the scope. At this time, the str in the scopetest () function is initialized in the entire function, and no value is assigned, therefore, execute print to output undefined.

Make a small modification and define STR in scopetest as a global variable. The result is easy to understand.

VaRStr= "Global";
FunctionScopetest (){
Print (STR );
Str= "Local";//STR is a global variable.
Print (STR );
}
Scopetest ();

The result is

    global  
Local
is actually the relationship between global variables and the scope of local variables, javascript has no block scope, which affects the scope of local variables, resulting in some special situations.
I do not know whether the understanding is reasonable. Please advise.
A lot of unreasonable points. I feel more reasonable about the resolution here. reply on the 12th floor.

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.