编程知识 cdmana.com

Understand JavaScript scope thoroughly

These are all basic articles , Maybe many people will say that the foundation is not very important , For so long , It doesn't use much foundation <font color="gray">( First of all, congratulations , It's on the optimized list ahead of time )</font>.

Now let's answer in detail what the basis is .

let  knowledge ,  Basics  

if ( knowledge  === '') {
   Basics  = ' The foundation '
}
if ( knowledge  === '') {
   Basics  = ' The root '
}
if ( knowledge  === ' sky ') {
   Basics  = ' ladder '
  console.log(' Basics  makes you up, up, up……  Until you meet ') 
}
………………

What about? ? Realize the importance of foundation , If there is no foundation , Code is like rootless wood , Castles in the air , Though it is pleasing to the eye , But it's always short .

Until you really understand Bottom How it works , You can really do it He let himself be strong , The wind blows the mountain ; He's from him , The bright moon shines on the river .

Far away , closed ~

Back to our point . Today I'll take you to the following JavaScript Scope issues in . Please wait and see .( own get a key ).

Let's start with the basics .

1. What is scope

The question of what the scope is , Many people can't answer well . Please note that : Generally speaking , Scope is to limit the use of a variable in a program .

Soga , Suddenly there was a kind of “ Twelve years in the same trade , I don't know Mulan is a girl ” To catch up with .

1.1 Global and local

After knowing the name of the scope . Let's meet it .

stay JavaScript The boundary of scope in is divided by function . Yes overall situation and Local Scope .

  • Global scope : The statement in <script></script> Variables in tags or Don't use var Declared variables It's available throughout the program , So called Global scope .
  • Local scope : The statement in Function body The variable of , It is available in the entire function execution environment and within its sub functions , But it's not accessible outside the function , So called Local scope

Xiao Lizi is on the stage :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

</body>
</html>
<script>
  var global = " I'm a global variable , I can be seen all over the world ";
    global = " I'm also a global variable , I can be seen all over the world ";
  function getName() {
    var name = " I'm a local variable , Only in getName You can find me in a function "
  }
</script>

1.2 Pre parsing and variable Promotion

See the title of the students will not be a little stunned . What is pre parsing ? What is variable promotion ?( If you know the answer, please cooperate with the boring author , Pretend to be in a daze .)

Cough ~ Not busy , Wait for the great God ( the ) To explain .

Pre parse It's before the program is executed , There will be a preview . Find the current Scope Internal cause function and var . And every time the scope is changed, it is executed in this scope Pre parse

Variable Promotion Refer to , In search of function and var after , First, define the default scope at the top of the current scope .var The default value is undefined, function The default value is The function itself .

notes :

​ image var getName = function() {} This code is defined as a variable , Not as a function definition .

“ Excuse me , Excuse me ……” In the distance, little chestnuts come rolling with a lot of code ~~

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>

</body>
</html>
<script>
  console.log(global) // undefined
  console.log(getName) // function getName(){}

  var global = 1;
  function getName () {}
</script>

EH ? How can this be ? I'm not defining global Do you ? How can output undefined Is it javascript There is bug?

Don't think much , In the process of pre parsing and variable Promotion , It doesn't assign values to variables , It's just a definition , It's not assigned until it's actually executed . Change the code , stay global Print again below the variable .

var global = 1;
console.log(global); // 1

explain : When it comes to the print function ,global Has been assigned to 1. It's already in The phase of code execution , Not in the pre parsing phase .

Practice your hands first :

Guess , How the following program outputs .

console.log(a) // 1
var a = 1;
console.log(a) // 2
getName()
function getName () {
  console.log(a) // 3
  console.log(b) // 4
  a = 2;
    console.log(a) // 5
  var b = 3;
    console.log(b) // 6
  function b(){}
}

What's your answer at this point ?

For the code above , Let's look at it graphically Pre parse Implementation process of .

image

ps:( The picture is too complicated , It takes patience to finish )

1.3 var and function The priority of the

Careful students may find a problem , The above code , stay getName Function , I have defined b Variable , It also defines b function . Why is it console.log(b) // 4 It will output when undefined

Because in the process of pre parsing , First search function Then look for var therefore ,function Will be var Cover . Here we will understand it as In the pre parsing process ,function Has a higher priority than var. The higher priority will be covered by the lower priority ( Is it very winding ? No problem , Think about it , Deepen your understanding of )

2. Scope chain

We've talked about scope chain execution before , Did anyone notice ? Is there any ?

ok , No one answered me , No one seems to notice .

It's in the training code ,getName() Within the function , Upward search a The process of variables , That is the search process of scope chain .

Idle time , Big picture in HD :

image

<font color="red"> Particular attention :</font> Scopes can only be found from the bottom up , Irreversibly to .( Variables inside functions cannot be accessed from outside functions )

3. Get the variables inside the function from the global

It says , It is not accessible to access variables inside a function outside of a function , If I insist on visiting ?( In general , This kind of person is easy to be beaten ).

ok , Since you are going to visit , There's a way , We can return variables inside functions , So you can access the variables in the function .

It's no use saying more , The code is the most practical :

console.log(getA()); //  In this way , We can visit  a  Variable .

function getA() {
  var a = 1;
  return a;
}

Spread your mind , Do you know any other ways ?

4. Block level scope

stay ES6 When it comes ,javascript Usher in a new concept ,-- Block level scope . seeing the name of a thing one thinks of its function , Block level scope allows variables to take effect in only one block of code .

Take a chestnut :

{
  var a = 1
}
console.log(a)

The code in the chestnut above will output normally , But the code below throws a Variable undefined error a is not defined.

{
  let a = 1;
}
console.log(a)

in other words a Variables only work in curly braces , It's not accessible outside curly braces .

There are two ways you can declare block level scopes .let and const .

So far, , We see three ways to define variables , Next , Let's see the difference between them .

4.1 var、let、const Similarities and differences

Same as : You can declare variables .

different :

var There is a local scope , Variable Promotion , The declared value can be changed .
console.log(a)
var a = 1;
a = 2;
//  All of the above operations are OK 
let There are block level scopes , Non variable Promotion , The declared value can be modified .( You can only declare variables first , And then use )
console.log(a) //  Will report a mistake ,  a is not defined
let a = 1;
a = 2;
const There are block level scopes , Non variable Promotion , The declared value itself is not modifiable ( You can only declare variables first , And then use )
const a = 1;
a = 2; //  Will report a mistake ,a Do not modify the 

//  The following conditions can be operated 
const a = []
a[0] = 1;

Be careful :

  • const Declared is called constant , You can't modify itself , But if you declare an object of a complex type , The value in the object is modifiable .

Here you will find a problem , The functions of the three are gradually enhanced .

4.2 TDZ Introduce ( Temporary dead zone ) Why? let and const You can't raise variables .

Use let and const Declared variables , stay Pre parse The variable will be put into a temporarily inaccessible interval , At this point, the access variable will prompt undefined error , After assigning a value to a variable , Put variables into the normal execution environment . Make variables accessible .

console.log(a) //  At this time a stay TDZ in 
let a = 1;     //  take a from TDZ Move it out 
console.log(a) //  At this point, you can access a Variable 

I believe you are full of energy now , Open your code , Learn to analyze the sequence of each step .

版权声明
本文为[yancy]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225143156578D.html

Scroll to Top