编程知识 cdmana.com

JS contains the function code

var a = 0
if (true) {
  a = 1 
  function a() {}
  a = 2
  console.log(' Inside ', a);
}
console.log(' outside ', a);
 Copy code 

Today, let's delve into this problem !!! After reading this topic ??? It's not very simple ???if Inside is the output 2 Do you ? What's outside is the output 0 Do you ? If it's that simple . You won't say it , First, we use variable promotion to ( Compile phase ) say something ( Without giving a variable of type, we default to var) Let's review variable improvement first

console.log(a) //function a
var a=0
console.log(a) //0
function a(){}
console.log(a) //0
 Copy code 

Let's first look at what the variable looks like after it is raised :()

function a(){}
console.log(a)
a=0
console.log(a)
console.log(a)
 Copy code 

Then the execution phase is to a assignment

 When executed a=0 when 
a The value of is changed to 0
 So the next two console.log(a) Output 1
 Copy code 

Here we change the code :

if (true) {
    console.log(a)//function a(){}
  a = 1 
  function a() {}
  console.log(a)//1
  a = 2
  console.log(' Inside ', a); //2
}
console.log(' outside ', a); //1
 Copy code 

Why I don't have a global definition a, Outside console.log(a) But it can output a Well ? because if( It was used let perhaps function Form a block level scope ) Inside is a block level scope , Here is an important sentence : In the block level scope, the function name variable will be synchronized to the function scope So this function Where is the scope of the function ? yes window. No one calls , yes window call , So it is window. Then that sentence will be understood : The scope of the function is window, The function name is a, This code has a variable with the same name as the function name . Should we also synchronize to the function scope ?

 Variable Promotion !!!
var a=undefined
if(true){
// Promotion of block level scope 
function a(){}
console.log(a)
a=1
console.log(a)
a=2
 console.log(' Inside ', a); 
}
console.log(' outside ', a); 
 Copy code 

Come back to the original code :

if (true) {
    console.log(a)//function a(){}
  a = 1 
  console.log(a)//1
  function a() {}
  a = 2
  console.log(' Inside ', a); //2
}
console.log(' outside ', a); //1
 Copy code 

Why do you output 1? Because in the execution phase, when the execution reaches a=1 When , to a assignment 1, When read function a(){} when , This function a() Yes, the function is also in the block level scope , So a variable with the same name as the function name will be Sync ( A copy of ) To the scope of the function , So the overall situation has a, front a Assigned to 1. So external output a. hinder a=2 It is given to the block level scope a.

版权声明
本文为[Live a good life]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/09/20210909122358680b.html

Scroll to Top