web front end development specification manual, 95 pages, notes sharing of primary front end module

Mind map

closure

Before understanding closures, let's learn about the memory release of the parent scope and stack.

Concept of parent scope

  • Where is the parent scope of a function created and who is the parent scope
var a = 10
function foo(){
    console.log(a)
}

function sum() {
    var a = 20
    foo()
}

sum()
/* output
    10
/
Copy code

The function foo() is created globally, so the parent scope of a is window and the output is 10

Thinking questions

var n = 10
function fn(){
    var n =20
    function f() {
       n++;
       console.log(n)
     }
    f()
    return f
}

var x = fn()
x()
x()
console.log(n)
/* output
*  21
    22
    23
    10
/
Copy code

Idea: what is the return value of fn? The variable x is what. Here, the return value of fn is the function name F, that is, the heap memory address of F. x() means that the function f() is executed instead of fn(). The output result is obvious

  • About how to find parent scopes

reference resources: Thoroughly solve the interview questions of JS variable promotion

JS stack memory free

  • Heap memory: stores reference type values, object types are key value pairs, and functions are code strings.

  • Heap memory release: assign the spatial address variable of reference type to null, or the browser will release this address when no variable occupies heap memory

  • Stack memory: provides the environment for code execution and stores basic type values.

  • Stack memory release: generally, the private scope of the function will be released after the function is executed.

However, there are special cases for the release of stack memory: ① after the function is executed, but there are contents in the private scope of the function that are still used by variables outside the stack, the stack memory cannot be released, and the basic values inside will not be released. ② The stack memory in the global environment will only be released when the page is closed

What is a closure

Definition of closure in JS Ninja script (P90): closure allows functions to access and operate variables outside functions. The definition of closure in the Red Book: closure refers to a function that has the right to access variables in the scope of another function. MDN defines closures as: closures refer to functions that can access free variables. The free variable here is the variable in the scope of the external function.

In summary, a closure is a function that has access to a variable in the scope of another function

Reasons for closures

If the internal function has a reference to the external scope, it will lead to closure. In fact, there is an example of closure from the concept of parent scope introduced above. return f is an expression.

var a = 0
function foo(){
    var b =14
    function fo(){
        console.log(a, b)
    }
    fo()
}
foo()
Copy code

There are references a and B of the external scope in the sub function fo memory, so this will produce closures

Function of closure

  • Protect the private variables of the function from external interference. Form stack memory that is not destroyed.
  • Save, save the values in some functions. Closures can privatize methods and properties

Closure classic usage scenario

    1. return returns a function
var n = 10
function fn(){
    var n =20
    function f() {
       n++;
       console.log(n)
     }
    return f
}

var x = fn()
x() // 21
 Copy code

return f, f() here is a closure, and there is a reference to the superior scope.

    1. Function as parameter
var a = 'Lin 11'
function foo(){
    var a = 'foo'
    function fo(){
        console.log(a)
    }
    return fo
}

function f(p){
    var a = 'f'
    p()
}
f(foo())
/* output
*   foo
/ 
Copy code

Use return fo to return. fo() is the closure. The parameter f(foo()) executes is the function fo. Because the parent scope of a in fo() is the function foo(), the output is foo

    1. IIFE (self executing function)
var n = 'Lin 11';
(function p(){
    console.log(n)
})()
/* output
*   Lin 11
/ 
Copy code

It also generates the closure p(), which exists in the reference n under the window.

    1. Cyclic assignment
for(var i = 0; i<10; i++){
  (function(j){
       setTimeout(function(){
        console.log(j)
    }, 1000) 
  })(i)
}
Copy code

Because of the existence of closures, the above can output 1 ~ 10 in turn, and closures form 10 private scopes that do not interfere with each other. After removing the outer self executing function, there is no reference to the external scope, and the output result is 10 consecutive. Why is 10 continuously output? Because JS is single threaded, asynchronous code will not be executed first (will be put on the stack). Asynchronous code will not start to execute until i + + to 10 of synchronous code is executed. At this time, i=10 and 10 are output.

    1. Using callback functions is using closures
window.name = 'Lin 11'
setTimeout(function timeHandler(){
  console.log(window.name);
}, 100)
Copy code

What should I pay attention to when using closures

It is easy to cause memory leakage. Closures carry the scope of other functions, so they occupy more memory than other functions. Overuse of closures can lead to excessive memory consumption, so use closures with caution.

Classic interview questions

  • for loops and closures (so-called must brush questions)
var data = [];

for (var i = 0; i < 3; i++) {
  data[i] = function () {
    console.log(i);
  };
}

data[0]();
data[1]();
data[2]()
/* output
    3
    3
    3
/
Copy code

i here is the global i, sharing a scope. When the function is executed, i=3, resulting in the output structure of 3.

  • Use closures to improve the above writing method to achieve the desired effect. Writing method 1: self executing functions and closures
var data = [];

for (var i = 0; i < 3; i++) {
    (function(j){
      setTimeout( data[j] = function () {
        console.log(j);
      }, 0)
    })(i)
}

data[0]();
data[1]();
data[2]()
Copy code
  • Writing 2: use let
var data = [];

for (let i = 0; i < 3; i++) {
  data[i] = function () {
    console.log(i);
  };
}

data[0]();
data[1]();
data[2]()
Copy code

let has a block level scope, and the three private scopes formed do not interfere with each other.

last

I would like to share the knowledge points involved in the real interview questions of big companies such as byte beating, meituan and headlines, as well as my personal learning methods and learning routes. Of course, I have also sorted out some learning documents and materials, which are attached to you. The knowledge points are relatively comprehensive, including but not limited to front-end foundation, HTML, CSS, JavaScript, Vue, ES6, HTTP, browser, algorithm, etc

Receive detailed answers to interview questions, learning notes, learning videos and other materials from large factories, Click the data collection through train Free!

Front end video data:
The knowledge points involved in the real interview questions of large factories such as, meituan and headlines, as well as my personal learning methods and learning routes. Of course, I have also sorted out some learning documents and materials, which are attached to you. The knowledge points are relatively comprehensive, including but not limited to front-end foundation, HTML, CSS, JavaScript, Vue, ES6, HTTP, browser, algorithm, etc

Receive detailed answers to interview questions, learning notes, learning videos and other materials from large factories, Click the data collection through train Free!

[external chain picture transferring... (img-B4yAC0qO-1627014459777)]

Front end video data:

Keywords: Front-end Interview Programmer

Added by Blissey on Sat, 15 Jan 2022 05:59:54 +0200