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