Article directory
A better way to learn scope is to simulate this process as a conversation between several people.
list of actors
What actors are involved in the work of scope and variables?
- Engine: responsible for the compilation and execution of JS programs
- Compiler: responsible for syntax analysis and code generation
- Scope: collects and maintains a set of queries consisting of all variables and enforces a strict set of rules for determining access rights
dialogue
When you see var a = 2
the , you think there's a statement, but it's actually two parts:
- Encounter
var a
:
The compiler asks whether the scope has a variable with the name that exists in the same scope set,
if so, ignore it, and continue compiling, otherwise the scope is required to declare a new variable and name ita
. - The compiler then generates the code required for the engine to process
a = 2
the
When the engine runs, it asks whether there is a variable in the scopea
. If so, use it directly, otherwise continue to search.
LHS and RHS
The compiler generates code in the second step, and when the engine executes it, it looks up the variable a
to determine whether it has been declared, which is LHS
the query. The query
is to find the value of a variable, that is, to obtain the source value of a variable, for example, the reference to in is a reference.RHS
console.log(a)
a
RHS
understand an example
function func(a){
console.log(a)
}
func(3)
- This code has
RHS
bothLHS
, first of all,func(3)
the function call must first findfunc
the value of the function object, which is aRHS
reference . - When passed
3
as a parameter tofunc
,3
it is implicitly passed toa
this variable,a
which is aLHS
reference to find in this case. console
Then do aRHS
query on this object and check if there is a methodlog
called .- Next, a query
a
is performed onRHS
, because the source valuea
of .