Understand the use of scope and closure in JS (Part 1) (basic definition)

foreword

What is scope? What is a closure? These are common questions in front-end interviews. Today, I will summarize the content of scope and closure.

Scope and Free Variables

Scope:
The scope can be understood as the legal scope of use of a variable. For the function as shown in the figure below, I have added layers of red boxes to it. The variables defined in each layer have its own scope of use.

insert image description here
There are three scopes:

  1. Global scope
    Write a variable directly in the code, the variable is not constrained and can be used globally
  2. Function Scope
    Variables defined in a function can only be used in the function
  3. Block-level scope (new in ES6)
    insert image description here
    The x variable defined in if(true) can only be used inside, and an error will be reported outside

Free variable:

  • A variable is not defined in the current scope, but is used
  • To the upper scope, search layer by layer until found
  • If it is not found in the global scope, an error xx is not defined will be reported

Closure

The special case of scoped application has two manifestations:

  1. function is passed as parameter
  2. The function is returned as the return value

Let's look at two examples:

insert image description here

The answer is to print 100
and then look at the following: the
insert image description here
printed value is still 100.

The function execution in Figure 1 is in the global scope, and a=200 is also in the global scope. Everything in the create function is in the function scope, so printing a to look for the upper-level scope is a=100

For the same reason in Figure 2, print a in the fn function and search for the upper scope, that is, a=100

Summary:
Closure: The search for free variables is where the function is defined, and the upper scope is searched,
not where it is executed!!!

assignment of this

Use of this:

  1. as a normal function
  2. use call apply bind
  3. is called as an object method
  4. call in class method
  5. arrow function

The value of this is confirmed when the function is executed, not when it is defined.
Look at the following examples. The use of this The
insert image description here
insert image description here
insert image description here
insert image description here
above example is relatively simple. With comments, you should be able to understand the six use cases of this.

finally

This article introduces you to the basic concepts of scope and closure, and also introduces several usage scenarios of this. The next article will start with a few real interview questions to further understand the use of scope and closure~

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123829172
Recommended