JavaScript learns its own understanding of scopes and scope chains

Source: Internet
Author: User

In JavaScript learning the scope and scope of the chain is relatively difficult to understand, the following I about the JavaScript scope and scope chain to do a detailed introduction, to give you beginners to answer questions.
Let's start by introducing what is a scope?
Literally understanding is the area that works.
There are two main scopes of scope:
1, block-level scope (JS is not supported): mainly used in C-series language, for example: Java Object-c/swift (Apple Development language), c++/c#. Do not make too many instructions here.
2, the scope of the lexical scope of a variable, the code is written out of the moment it is determined, will not be affected by the operation of the code.
In other words, the scope of the variable is only relevant to where the code is declared, regardless of the runtime. In JavaScript only functions can form a scope, all in the JS morphemes scope is also called function scope.
What is a scope chain?
Scope Chain: Each function forms a scope, and if the function is wrapped by another function, the parcel function has scope and goes up to the global environment. This creates a chain of scopes.
Say so many concepts, it must be boring, just look at an example:

 <script type= "Text/javascript" >  function   FN ()  { Span style= "color: #0000ff;"            >var  a = 456;  function  < Span style= "Background-color: #ff00ff;"                > foo ()  { var  num = 123;  function   F ()  {}} foo (); } 
</script>

We can tell from the example that the function FN is wrapped in function foo, and the function foo is wrapped in the relationship of function f
The region that the script label wraps is the global scope
Scope chain of F: F-scope->foo scope->FN scope-global scope.
Foo's scope chain: Foo scope->FN scope-global scope.
The scope chain of FN: The global scope, FN scope.
Is there a clear understanding of the scope?

JavaScript learns its own understanding of scopes and scope chains

Related Article

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.