Simple understanding of scope in JavaScript, as well as left and right references (scope and closure - Ch1.2)


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 = 2the , 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 it a.
  • The compiler then generates the code required for the engine to process a = 2the
    When the engine runs, it asks whether there is a variable in the scope a. 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 ato determine whether it has been declared, which is LHSthe 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.RHSconsole.log(a)aRHS

understand an example

function func(a){
    
    
	console.log(a)	
}

func(3)
  • This code has RHSboth LHS, first of all, func(3)the function call must first find functhe value of the function object, which is a RHSreference .
  • When passed 3as a parameter to func, 3it is implicitly passed to athis variable, awhich is a LHSreference to find in this case.
  • consoleThen do a RHSquery on this object and check if there is a method logcalled .
  • Next, a query ais performed on RHS, because the source value aof .

Guess you like

Origin blog.csdn.net/Littlelumos/article/details/128648606