Javascript scope and closure details

Javascript scope and closure details

1. Scope

Simply put, scope refers to the area in a program where variables are defined, which determines the access rights of the currently executed code to the variables.

In ES5, there are generally only two scope types:

  • Global scope: The global scope is the outermost scope of the program and always exists
  • Function scope: A function scope is created only when a function is defined and is contained in the parent function scope or the global scope.

After talking about the concept, let's look at the following code:

var a = 100
function test(){
    var b = a * 2
    var a = 200
    var c = a/2
    console.log(b)
    console.log(c)
}
test() // What will be printed here?

Analysis:

  • First, this code forms a global scope and a function scope
  • There is a variable a in the global scope with a value of 100
  • Local variables b, a, and c are defined in the test function scope.
  • There is variable promotion here. Variable promotion is first performed in the function scope: var b; var a; var c;
  • Then assign a value to b. At this time, a has not been assigned a value, so the value of a is undefined. Then a*2 is added, so b is NaN.
  • Then assign a a value of 200 and c a value of a/2, which is 100.

So it will print NaN, 100

In ES6, a new block scope is added

In simple terms, the area within the curly braces {...} is the block-level scope, but Javascript does not natively support block-level scope. You need to use let and const proposed by ES6 to create block-level scope.

// ES5
if(true) {
  var name = 'Nanjiu'
}
console.log(name) // Nanjiu // ES6
if(true) {
  let age = 18
}
console.log(age) // This will report an error

2. Scope Chain

When accessing a variable inside the executable code, it will first check whether the variable exists in the current scope. If it does, it will return immediately. If not, it will search in the parent scope... until it finds the global scope. We call this scope nesting mechanism作用域鏈

3. Lexical Scope

詞法作用域is a working model of scope. Lexical scope is a type of scope used in JavaScript . Lexical scope can also be called靜態作用域.

The so-called lexical scope is determined by where you write the variables and scopes when you write the code. That is, the lexical scope is a static scope, which is determined when you write the code. The scope of a function is determined by where it is declared, not where it is actually called.

MDN defines closures as follows:

A function is bundled with a reference to its surroundings (lexical environment) (or the function is surrounded by references). Such a combination is called closure .

In other words, closures allow you to access the scope of an outer function from within an inner function. In JavaScript , whenever a function is created, a closure is created at the same time as the function is created.

We can conclude that:

閉包= 函數+ 外層作用域

Let's look at the code first:

var name = 'Front-end Nanjiu'

function say() {
  console.log(name)
}
say()

Analysis: The say function can access the variable a in the outer scope, so doesn’t this form a closure?

There is a sentence in the book "Javascript Definitive Guide": Strictly speaking, all JavaScript functions are closures.

But this is just a theoretical closure, which is different from what we usually use. The example above is just a simple closure.

ECMAScript defines closures as follows:

  • In theory: all functions are closures. Because they have already saved the data of the upper context when they are created.
  • In practice, a closure should satisfy two conditions: 1. The variables of the outer scope are referenced in the code; 2. It still exists even if the context in which it was created is destroyed;

Let's look at another piece of code from the JavaScript Definitive Guide:

let scope = 'global scope'
function checkscope(){
  let scope = 'local scope'
  function f(){
    return scope
  }
  return f
}

let s = checkscope()   
s() // What does this return?

Many students may think it is global scope , but is it really so? Let's take a look at its execution process:

  • First, execute the global code, create a global execution context, define the global variable scope and assign it a value
  • Declare the checkscope function, create the execution context of the function, create the local variable scope and assign a value
  • Declare the f function and create the execution context of the function
  • Execute the checkscope function, which returns an f function and assigns it to the variable s
  • Executing the s function is equivalent to executing the f function. scope returned here is local scope . As for why it is local scope , we talked about lexical

Basic rules of scope: JavaScript functions are executed using the scope in which they are defined. In the scope where the f function is defined, the value of the variable scope is local scope

5. Application of closure

Closures are mostly used to maintain internal variables.

6. The flaws of closures

  • Since the existence of closures may cause variables to reside in memory, improper use may cause memory leaks
  • Memory leaks can cause your app to freeze or crash

7. Frequently asked closure interview questions

var arr = []
for(var i=0;i<3;i++){
    arr[i] = function(){
        console.log(i)
    } 
}
arr[0]() // 3
arr[1]() // 3
arr[2]() // 3
// Here, i has become 3 during execution

// Solve using closure var arr = []
for(var i=0;i<3;i++){
    arr[i] = (function(i){
        return function(){
            console.log(i)
        } 
    })(i)
    
}
arr[0]() // 0
arr[1]() // 1
arr[2]() // 2

This is the end of this article about Javascript scope and closure details. For more information about Javascript scope and closure, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS Difficulties Synchronous and Asynchronous and Scope and Closure and Detailed Explanation of Prototype and Prototype Chain
  • Detailed explanation of the usage of JavaScript scope, scope chain and closure
  • Detailed explanation of JavaScript scope closure
  • In-depth understanding of JS scope and closure
  • Detailed explanation of JavaScript function usage [function definition, parameters, binding, scope, closure, etc.]
  • JS page gets session value, scope and closure study notes
  • JavaScript uses closures to simulate block-level scope operations
  • Scope and Closures in JavaScript

<<:  Detailed explanation of CSS counter related attributes learning

>>:  Docker stop stops/remove deletes all containers

Recommend

Detailed explanation of JavaScript stack and copy

Table of contents 1. Definition of stack 2. JS st...

Web project development JS function anti-shake and throttling sample code

Table of contents Stabilization Introduction Anti...

js implementation of verification code case

This article example shares the specific code of ...

How to pull the docker image to view the version

To view the version and tag of the image, you nee...

Write a React-like framework from scratch

Recently I saw the article Build your own React o...

Solution to blank page after Vue packaging

1. Solution to the problem that the page is blank...

Solve the problem when setting the date to 0000-00-00 00:00:00 in MySQL 8.0.13

I just started learning database operations. Toda...

SQL to implement time series dislocation restoration case

Table of contents 1. Requirements description 2. ...

Detailed explanation of the lock structure in MySQL

Mysql supports 3 types of lock structures Table-l...

How to use history redirection in React Router

In react-router, the jump in the component can be...

Detailed graphic tutorial on installing centos7 virtual machine in Virtualbox

1. Download centos7 Download address: https://mir...

Method for realizing Internet interconnection by VMware virtual machine bridging

After installing VMware and creating a new virtua...

Optimized implementation of count() for large MySQL tables

The following is my judgment based on the data st...