Hear about lexical environment for the first time today… First time. What the hell is this? I just hehe. Js has closures, prototype chains, scope chains… Emmm got a new knowledge point today. Lexical environment is lexical environment, don’t underestimate. Hey! It also has categories.

  1. He is window’s father. Let’s start with the title:
console.log(a)
var a = 1
Copy the code

When you see the problem, you probably know about it, in fact, when we first learned it, but you don’t pay attention to it. Those with poor basic skills may think that output 1. Actually, the answer is undefined. Guess what. In terms of the global lexical context, it makes sense. The global lexical environment starts with the pre-processing stage, recording variables declared in the scope code first, excluding variables that are not declared by var. Log console.log(a). A is not assigned a value, so the output is undefined. 2. Function lexical environment First of all, in the pre-processing stage, the parameters of the function are recorded to the lexical environment and assigned values. Secondly, in the execution stage, assign values to the variables in the pretreatment, record the variables without var declaration to the global lexical environment, and assign values.

function f(a,b){
	console.log(a)
	var  a = 100
}
f(10.5)
Copy the code

I don’t know. The output is 10. In a functional lexical context, a is recorded but not assigned. During the execution phase, f assigns the value of parameter A not 10, parameter A and variable A are the same name and overwrite, in this case, the value of a is 10. So the output is 10. Here, I’m just giving two simple examples, but a more complicated one might result in the fact that I can read every line, and together I don’t know anyone. Take a look at this:

console.log(a)
console.log(b)
console.log(c)
console.log(d)
var  a = 1;
If(false)
     var  b = 2;
else
     c = 3
function f(){
	var d = 4
}
Copy the code

I don’t need to explain too much. First use the global lexical environment, record b (a ignored, d is not global),SO, the output is undefined. C is not defined, so the output is c is not defined. D is not defined in function f, and f is not executed, so d is not defined just like C. Similar topics are many, I think or need to pay attention to everywhere, otherwise, really like me even some professional terms have not heard.