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

Linux uses if to determine whether a directory exists.

How to use if in Linux to determine whether a dir...

Detailed explanation of building MySQL master-slave environment with Docker

Preface This article records how I use docker-com...

Json advantages and disadvantages and usage introduction

Table of contents 1. What is JSON 1.1 Array liter...

Vue3+TypeScript implements a complete example of a recursive menu component

Table of contents Preface need accomplish First R...

Using keras to judge SQL injection attacks (example explanation)

This article uses the deep learning framework ker...

Web front-end development course What are the web front-end development tools

With the development of Internet technology, user...

Mini Program to Implement Slider Effect

This article example shares the specific code for...

A brief analysis of the difference between static and self in PHP classes

Use self:: or __CLASS__ to get a static reference...

Causes and solutions for MySQL deadlock

The database, like the operating system, is a sha...

Docker images export and import operations

What if the basic images have been configured bef...

Detailed explanation of mysql user variables and set statement examples

Table of contents 1 Introduction to user variable...

Summary of knowledge points about events module in Node.js

Through the study and application of Node, we kno...

How to use resident nodes for layer management in CocosCreator

CocosCreator version: 2.3.4 Most games have layer...