01. Running mechanism of JavaScript
(1) All synchronization tasks are executed on the main thread, forming an execution stack.
(2) In addition to the main thread, there is a "task queue". As long as the asynchronous task has run results, an event is placed in the "task queue".
(3) Once all synchronous tasks in the Execution Stack are completed, the system will read the Task Queue to see what events are in it. Those corresponding asynchronous tasks end the waiting state, enter the execution stack, and begin execution.
(4) The main thread repeats the above three steps continuously. (Event cycle)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>00_Introduce</title> </head> <body> <div id="btn01"> <button>Test 11</button> <button>Test 12</button> <button>Test 13</button> </div> <hr/> <div id="btn02"> <button>Test 21</button> <button>Test 22</button> <button>Test 23</button> </div> <hr/> <div id="btn03"> <button>Test 31</button> <button>Test 32</button> <button>Test 33</button> </div> <!-- //Requirement: Click on a button and prompt "The nth button is clicked" --> <script type="text/javascript"> var btns01 = document.getElementById('btn01').getElementsByTagName('button'); var btns02 = document.getElementById('btn02').getElementsByTagName('button'); var btns03 = document.getElementById('btn03').getElementsByTagName('button'); console.log(btns01) // Something the matter JavaScript The running mechanism executes on the main thread to form an execution stack,Once all synchronous tasks in the Execution Stack are completed, the system reads the Task Queue. for(var i=0,length=btns01.length;i<length;i++) { var btn = btns01[i] console.log(btn) btn.onclick = function () { alert('The first'+(i)+'individual ' + btn.innerHTML) } } // Solution 1: Save Subscripts for(var i=0,length=btns02.length;i<length;i++) { var btn02 = btns02[i] btn02.index = i btn02.onclick = function () { alert('The first'+(this.index+1)+'individual ' + btns02[this.index].innerHTML ) } } // Solution II: Using closures for(var i=0,length=btns03.length;i<length;i++) { (function (i) { var btn03 = btns03[i] btn03.onclick = function () { alert('The first'+(i+1)+'individual ' + btn03.innerHTML ) } })(i) } </script> </body> </html>
02. Understanding closures
1. How to generate closures?
* Closure occurs when a nested internal (child) function refers to a variable (function) of a nested external (parent) function.
2. What exactly is a closure?
* Use chrome debugging to view
* Understanding 1: Closures are nested internal functions (most people)
* Understanding 2: Objects containing quoted variables (functions) (very few people)
* Note: Closures exist in nested internal functions
3. Conditions for generating closures?
* Function nesting
* Internal functions refer to data from external functions (variables/functions)
function fn1 () { var a = 3 function fn2 () { console.log(a) } fn2() } fn1()
03. Common closures
1. Use a function as the return value of another function
2. Passing a function as an argument to another function call
// 1. Regarding a function as the return value of another function function fn1() { var a = 2 function fn2() { a++ console.log(a) } return fn2 } var f = fn1() f() // 3 f() // 4 // 2. Pass a function as an argument to another function call function showMsgDelay(msg, time) { setTimeout(function () { console.log(msg) }, time) } showMsgDelay('hello', 1000)
04. The role of closures
1. Using variables within a function to survive in memory after the function is executed (prolonging the lifetime of local variables)
2. Make data (variables/functions) that can be manipulated (read and write) from outside to inside of a function.
Questions:
1. Do local variables declared within a function still exist after the function is executed?
2. Can local variables within a function be accessed directly outside the function?
function fun1() { var a = 3; function fun2() { a++; //Variables referring to external functions--->Generating closures console.log(a); } return fun2; } var f = fun1(); //Because f Referring to internal functions-->Neither internal functions nor closures are garbage objects f(); // 4 Indirect manipulation of local variables within functions f(); // 5
05. Closure life cycle
1. Generation: Generated when the nested internal function definition is executed (not called)
2. Death: When nested internal functions become garbage objects
function fun1() { //Here closures have been generated var a = 3; function fun2() { a++; console.log(a); } return fun2; } var f = fun1(); f(); f(); f = null //At this point, the closure object dies
06. Application of closures
Custom JS module
* js files with specific functions
* Encapsulate all data and functions in one function (private)
* Objects or functions that expose only one package of n methods
* Users of modules only need to use object invocation method exposed by modules to realize corresponding functions.
// Custom Module 1 function coolModule() { //Private data var msg = 'message' var names = ['I', 'Love', 'you'] //Functions for Private Operating Data function doSomething() { console.log(msg.toUpperCase()) } function doOtherthing() { console.log(names.join(' ')) } //Exposing objects that contain multiple methods return { doSomething: doSomething, doOtherthing: doOtherthing } }
var module = coolModule() module.doSomething() module.doOtherthing()
Custom Module 2
// Custom Module 2 (function (window) { //Private data var msg = 'atguigu' var names = ['I', 'Love', 'you'] //Functions for manipulating data function a() { console.log(msg.toUpperCase()) } function b() { console.log(names.join(' ')) } window.coolModule2 = { doSomething: a, doOtherthing: b } })(window)
coolModule2.doSomething()
coolModule2.doOtherthing()
07. Disadvantages and solutions of closures
1. Disadvantages
* After the function is executed, the local variables in the function are not released and the memory occupied time becomes longer.
* Easy to cause memory leak
2. Solution
* If you can do without closures, you can do without closures.
* Timely release
function fn1() { var a = 2; function fn2() { a++; console.log(a); } return fn2; } var f = fn1(); f(); // 3 f(); // 4 f = null // release
08. Interview questions
// Talk about their output //Code snippet 1 var name = "The Window"; var object = { name: "My Object", getNameFunc: function () { return function () { return this.name; }; } }; console.log(object.getNameFunc()()); //The Window //Code snippet 2 var name2 = "The Window"; var object2 = { name2: "My Object", getNameFunc: function () { var that = this; return function () { return that.name2; }; } }; console.log(object2.getNameFunc()()); // My Object
// Talk about their output function fun(n, o) { console.log(o) return { fun: function (m) { return fun(m, n) } } } var a = fun(0) a.fun(1) a.fun(2) a.fun(3) //undefined,0,0,0 var b = fun(0).fun(1).fun(2).fun(3) //undefined,0,1,2 var c = fun(0).fun(1) c.fun(2) c.fun(3) //undefined,0,1,1