JS Difficulties Synchronous and Asynchronous and Scope and Closure and Detailed Explanation of Prototype and Prototype Chain

JS Difficulties Synchronous and Asynchronous and Scope and Closure and Detailed Explanation of Prototype and Prototype Chain

JS Three Mountains

Synchronous Asynchronous

There are only two operations in the frontend that are asynchronous:

  • Timers execute asynchronously;
  • ajax asynchronous request

Compiler parsing + code execution principle:

1. The compiler parses the code one by one from top to bottom

2. Determine whether the code is synchronous or asynchronous

  • Synchronous: Execute immediately
  • Asynchronous: Not executed. Put into event queue pool

3. Wait until all synchronous executions are completed before starting asynchronous execution

The difference between synchronous and asynchronous

api: asynchronous with callback, synchronous without callback

Performance: Asynchronous performance is good (does not block threads) Synchronous will block threads

Order: synchronous in-order execution, asynchronous out-of-order execution

Another: Callback function: If a function's parameter is a function, then this parameter function is called a callback function

Scope, Closure

Function scope chain

  1. Only variables declared with var are recognized as function scopes.
  2. Only functions can open up new function scopes
  3. The default global area is called level 0 scope. Functions declared at level 0 will open a new scope, which we call level 1 scope.
  4. The function declared in level 1 creates a scope, and we have level 2 scope, and so on.
  5. Like a chain, it is called a scope chain

insert image description here

Block Scope

1. A {} is a block-level scope, let recognizes the block-level scope

2. For let, the default global scope is also called level 0 block scope. Then, in addition to objects, curly braces open up new block scopes. Level 0 opens up level 1, level 1 opens up level 2, and so on.

3. It is the same as the function scope chain we learned before, except that the function scope is only the function that opens the function scope, the block scope is the curly braces that open the block scope, var recognizes the function scope, and let recognizes the block scope

Closures

A closure is a function. Functions that can read variables inside other functions

Code example:

    function foo () {
      // foo's internal variable let num = 10
      // This inner is called a closure function inner() {
        console.log(num)
      }
    }

What is the use of closures?

  • Closure is like a bridge between the outside world and the inside of a function.
  • That is, using closures allows the outside world to access the variables inside the function.
There is a difference between closures and direct return values

Directly returning a value actually just returns the data of that value. Subsequent changes have nothing to do with the variables inside the function.

Therefore, using closures, the outside world can indirectly access the variables inside the function.

Several ways to write closures

Simply put: anything that meets the closure characteristics is considered a closure

Closure: is a function that allows the outside world to access the internal variables of the function

Closure effect 1: Extending the life cycle of variables

Life cycle: refers to the cycle from declaration to destruction

The life cycle of a global variable starts from the opening of a web page to the end of the web page

The life cycle of a local variable starts and ends in the scope in which it is located.

Because closures can extend the life cycle of variables, the outside world can still access local variables.

Therefore, extensive use of closures may cause memory leaks

Memory leak: A piece of data is no longer needed, but it still occupies memory space and has not been recycled.

Solution:

  • Just assign the closure value to null
  • Assigning a value of null means that no one has referenced the data. If no one has referenced it, it will be marked as "garbage" and will be recycled by GC at the appropriate time.
  • GC: Garbage Collection Mechanism
  • Chrome browser uses this mechanism
Closure effect 2: Restricting access

Make the variable a local variable so that it cannot be accessed directly from the outside world

It can only be accessed indirectly through the closure (bridge) we wrote, so that we can make some restrictions in the closure, thus achieving the purpose of limiting access.

Closure call precautions

Notice:

The number of times the outer function that generates the closure is called will generate the same number of closures, and different data will be operated on at that time.

If the outer function that generates the closure is called once, only one closure is generated, and the data operated on is still the same.

Closure solves the problem of subscript errors caused by using var

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }
    li {
      width: 30px;
      height: 30px;
      background-color: yellow;
      line-height: 30px;
      text-align: center;
      float: left;
      margin-right: 10px;
    }
  </style>
</head>
<body>
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
  </ul>
  <script>
    // Was there let before? No, so let's see how to solve the subscript problem using var // Find all li
    var lis = document.getElementsByTagName('li')
    for (var i = 0; i < lis.length; i++) {
      // Now there is only one variable in i, so when you finally click, everyone visits one i
      // The final value of i is 5, so no matter who you click, it will be 5
      // Solution: If I have 5 li, I need 5 variables, and the values ​​of the variables are 0, 1, 2, 3, 4 respectively
      // How can we generate 5 different variables? We need to create a function scope (function () {
        // Because this loop will generate 5 self-executing functions // This means there are 5 different index variables // and their values ​​need to be 0, 1, 2, 3, 4 respectively, and the values ​​of i are exactly 0, 1, 2, 3, 4
        // So just assign i to index var index = i
        // Add a click event to each li lis[i].onclick = function () {
          alert(index)
        }
      })()
    }
  </script>
</body>

</html>

Voting Machine

    // To make a function that can vote and get the current number of votes function votor() {
      // There is a variable to store the number of tickets let ticket = 0
      return {
        getTicket: function () {
          console.log('The current number of tickets is: ' + ticket)
        },
        // Voting add: function () {
          ticket++
        }
      }
    }
    let tp = votor()
    tp.add()
    tp.add()
    tp.add()
    tp.add()
    tp.getTicket()

Two interview questions about closures

		// Question 1:
        window.name = "The Window"; 
        let object = {
            name: "My Object",  
            getNameFunc: function () { 
                return function () {
                    return this.name;
                };
            }
        };
        console.log(object.getNameFunc()());  
                 // Question 2:
        window.name = "The Window";
        let object = {
            name: "My Object",  
            getNameFunc: function () { 
                let that = this; 
                return function () {
                    return that.name;
                };
            }
        };
        console.log(object.getNameFunc() ());

Prototype, prototype chain

Prototype Object

effect:

​ Adding common properties and methods in the constructor to the prototype object can save memory

Prototype chain

No matter which object you start from, you can find Object.prototype by searching upwards according to proto. This chain of objects connected in series using __proto__ is called a prototype chain.

Complete prototype chain diagram

Schematic diagram prerequisites:

Each object has a __proto__ attribute, which points to the prototype object of the constructor function;

Every object has a prototype property, which is an object;

Functions are objects too;

When an object does not have an exact constructor to instantiate, we regard it as a built-in constructor.

An instance of Object; Object's prototype is the top-level prototype object, and its __protype__ points to null ;

Function is a top-level constructor. It is its own constructor and its own instance object (in layman's terms, it creates itself).

Schematic diagram of the complete prototype:

insert image description here

The above is the detailed content of the detailed explanation of the difficult JS synchronous and asynchronous scope, closure prototype and prototype chain. For more information about JS synchronous and asynchronous scope, closure prototype and prototype chain, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Javascript scope and closure details
  • 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

<<:  Summary of Common Problems with Mysql Indexes

>>:  Docker connection mongodb implementation process and code examples

Recommend

vue3 custom directive details

Table of contents 1. Registering custom instructi...

Learn MySQL index pushdown in five minutes

Table of contents Preface What is index pushdown?...

How to connect to MySQL database using Node-Red

To connect Node-red to the database (mysql), you ...

Semantics: Is Html/Xhtml really standards-compliant?

<br />Original text: http://jorux.com/archiv...

MySQL Oracle and SQL Server paging query example analysis

Recently, I have done a simple study on the data ...

How to deal with time zone issues in Docker

background When I was using Docker these two days...

The difference between br and br/ in HTML

answer from stackflow: Simply <br> is suffic...

Introduction and tips for using the interactive visualization JS library gojs

Table of contents 1. Introduction to gojs 2. Gojs...

js method to delete a field in an object

This article mainly introduces the implementation...

Vue realizes simple effect of running light

This article shares the specific code of Vue to a...

How to upload projects to Code Cloud in Linux system

Create a new project test1 on Code Cloud Enter th...

A brief introduction to the command line tool mycli for operating MySQL database

GitHub has all kinds of magic tools. Today I foun...

Solution to 404 error when downloading apk file from IIS server

Recently, when using IIS as a server, the apk fil...