1. callback function
-
Asynchronous: when doing an operation, you can do other things
-
Synchronization: when doing an operation, others can only wait for alert for
//-Asynchronous: when doing an operation, you can do other things timer console.log(1); setTimeout(function () { console.log("timer"); }, 2000); console.log(2); // -Synchronization: when doing an operation, others can only wait alert for alert(1); alert(2);
-
Callback function: it is an effective way to solve asynchronous operation by passing it as a parameter to other function calls
-
Call: call after an action or an action is executed.
//Callback function: pass the function as a parameter to other function calls, and solve the asynchronous operation effectively. When an action or a behavior is executed, it will be called. setTimeout(fun, 3000); function fun() { console.log("Callback function"); }
2. Anonymous function self execution (IIFE)
2.1 types of functions
-
Anonymous function: a function without a name
-
Learned function types
//1. Ordinary function function fun1(){ console.log("Ordinary function"); } //2. Expression function var fun2 = function (){ console.log("Expression function"); } fun2(); //3. Event handling function document.onclick = function(){ console.log("Event handler"); } //4. Callback function setTimeout(function(){ console.log("Callback function");},2000); //5. Anonymous function function (){ console.log("Anonymous function"); }
2.2 anonymous function self execution
-
Anonymous function: a function without a name
//2. Anonymous function self execution (function declaration) (call) (function () { console.log("Anonymous function"); })();
-
Anonymous function parameters
//3. Function parameter transfer (function (a, b) { var c = a + b; console.log(c); })(10, 20);
-
Anonymous function return value
//4. Return value var s = (function (a, b) { var c = a + b; return c; })(10, 20); console.log(s);
2.3 features and usage scenarios
-
Usage scenario
-
Add an anonymous function self execution at the beginning of the external js file
-
Add functionality without affecting other code
-
Used in closures
-
-
advantage:
-
Avoid global pollution (global pollution (global variables are widely used, and global variables can be modified arbitrarily)
-
Perfect embedded code
-
-
Note: when you write anonymous functions, you should add;
;(function(){ console.log("Anonymous 1"); })() ;(function(){ console.log("Anonymous 2"); })()
3. Closure function
3.1 review
-
Local variable characteristics
//Characteristics of local variables and functions function fun(){ var a = 10; //Local variables cannot be used by the outside world, except that the parentheses of the function will be destroyed console.log(a++); } fun(); fun();
3.1 closure Basics
-
Concept of closure: functions that can access internal variables of other functions (function sets, internal functions can access external function variables)
-
Features: extend the use range of variables. Variables used in closures will always be stored in memory, similar to global variables, to avoid pollution
-
Disadvantages: it may cause memory leakage. Use it with caution and release it when not in use. f = null;
//1. Closure: functions that can access internal variables of other functions (function sets, internal functions can use external function variables) function outer(){ var s = 100; function inner(){ console.log(s); //100 } inner(); } outer(); //2. Complete closure function wai(){ var c = 10; return function (){ console.log(c++); } } var inn = wai(); //inn = function(){console.log(c++);} inn(); //10 inn(); //11 inn(); //12 inn(); //13
-
Each closure is an independent module and has no influence on each other
//2. Complete closure function wai(){ var c = 10; return function (){ console.log(c++); } } var inn = wai(); //inn = function(){console.log(c++);} inn(); //10 inn(); //11 inn(); //12 inn(); //13 //Each closure is an independent module and has no influence on each other var inn2 = wai(); //inn2 = function(){console.log(c++);} inn2();
3.2 use scenarios of closures
-
Usage scenario 1: use function internal variables
//1. Use variables inside the function function outer() { var a = 10; return function () { console.log(a++); } }
-
Usage scenario 2: solve the global scope problem
//2. Solve the global scope problem var arr = []; for (var i = 0; i < 5; i++) { arr.push(function () { console.log(i); }) } //What is the result of code execution? //Arr [fun, fun, fun, fun] I = 5, the condition does not hold, end the cycle // arr[3]() = function(){console.log(i)} arr[3](); //5 arr[2](); //5 //Modify with closures var arr1 = []; for (var i = 0; i < 5; i++) { (function (i) { //var i; arr1.push(function () { console.log(i); }) })(i); } arr1[3](); //3 arr1[2](); //2
-
Usage scenario 3: private attributes
//3. Private attribute (idCard is invisible to the outside world and can be set and obtained) function Person() { //this.idCard = "431102200312124568"; var idCard = "431102200312124568"; return { "getId": function () { return idCard; }, "setId":function(id){ idCard = id; } } } var p = new Person(); // p = function(){ return idCard;} console.log(p); //Get id console.log(p.getId()); //431102200312124568 //Set id p.setId("431102200412122222"); console.log(p.getId()); //431102200412122222
-
Usage scenario 4: anti shake and throttling
3.3 closed surface test questions
-
Interview question 1: how to modify the result after running the code
//1. Interview question 1: i is a global variable and becomes a local variable var arr = []; for (var i = 0; i < 5; i++) { (function (i) { //var i arr.push(function () { console.log(i); }) })(i); } arr[3](); //3 arr[2](); //2
-
Interview question 2: using closures to simulate private variables
//2. Closure interview question: use closure to simulate private attribute id, which is invisible to the outside world function Person() { // this.idCard = "431102200312124568"; //If it is set as a local variable, you can't see it outside, but the function parentheses will be destroyed var idCard = "431102200312124568"; //Form a closure. The variables used in the closure will always be stored in memory and will not be destroyed return { "getId":function(){ //Function to get id return idCard; }, "setId":function(id){ //Function to set id idCard = id; } } } var p = new Person(); console.log(p); //{getId: ƒ, setId: ƒ} console.log(p.getId()); p.setId("431102200312124560");
-
Interview question 3: what is the result of code execution
//3. Closure interview 3: results after code execution function fun(n,o){ console.log(o); return { "fun":function(m){ return fun(m,n); } } } /* var a = fun(0,undefined) Variables used in closures are always stored in memory, n = 0 a = { "fun":function(m){ return fun(m,n); } } a.fun(1) //m = 1; fun(1,0) a.fun(2) //m = 2; fun(2,0) a.fun(3) //m = 3; fun(2,0) */ var a = fun(0); //undefined a.fun(1); //0 a.fun(2); //0 a.fun(3); //0
-
Interview question 4: what is the result of code execution
//4. Closure interview 4: look at the code and write the program for(var i = 0;i<5;i++){ setTimeout(function(){ console.log(new Date(),i); //Thu Aug 26 2021 15:03:50 GMT+0800 (China standard time) 5 },1000); } console.log(new Date(),i); //Thu Aug 26 2021 15:03:49 GMT+0800 (China standard time) 5
4. Recursive function
-
Recursion: call the function itself inside the function
-
The difference between the loop and the loop: the infinite execution of the loop will become an dead loop and get stuck. The recursion has the maximum number of stack calls. If it exceeds, an error will be reported
4.1 factorial
-
Recursive implementation process
-
Find rules
-
Recursion: call the function itself inside the function
-
Return: end the recursive execution at the beginning of the function
//1. Find the law first //6! Factorial 6 * 5 * 4 * 3 * 2 * 1 //6! 6 * 5! //5! 5 * 4! //4! 4 * 3! //n! = n * (n-1) //2. Pass through: / / exceeds the maximum call stack size // function jc(n) { // return n * jc(n-1); // } // jc(6); //3. Return (must end) function jc(n){ //Return: must be the beginning of the function if(n == 1) return 1 //Deliver return n * jc(n-1); // return n * jc(n-1); // // 6 * jc(5) 6*5*4*3*2*1 // //5 * jc(4) 5*4*3*2*1 // //4 * jc(3) 4*3*2*1 // //3 * jc(2) 3*2*1 // //2 * jc(1) 1 // //1 } console.log(jc(10));
-
4.2 Fibonacci series
-
Sequence features: 1,1,2,3,5,8,13,21,34...
-
Sequence Law: f(n) = f(n-1) + f(n-2)
//1. Find the law 1 1 2 3 5 8 13 21 34 //f(6) = f(5) + f(4) //f(5) = f(4) + f(3) //2. Delivery // function rabbit(n){ // return rabbit(n-1) + rabbit(n-2); // } // console.log(rabbit(6)); //8 //3. Attribution function rabbit(n){ if(n == 1 || n == 2) return 1; return rabbit(n-1) + rabbit(n-2); } console.log(rabbit(6)); //8 console.log(rabbit(9)); //34
4.3 quick sort
-
Realization idea
arr.length <=1 return arr; var arr = [2,7,1,5,4,6,8] 1.Gets the element in the middle of the array (Remove intermediate elements from array) var middle = arr.aplice(arr.length/2,1)[0]; 2.Create two empty arrays, left,right 3.The loop array is compared with the middle value, and the array smaller than the middle value is put left,Those larger than the middle value are put behind middle = 5 left = [2,1,4] right = [7,6,8] 4.combination return quick(left).concat(middle,quick(right))
-
code implementation
function quick(arr) { //5. Conditions for ending recursion if(arr.length<=1) return arr; //1. Find the intermediate value (delete the intermediate value) var middle = arr.splice(Math.floor(arr.length / 2), 1)[0]; //2. Create two empty arrays var left = []; var right = []; //3. Compare the circular array with the middle value, and put the smaller one in the front and the larger one in the back for(var i = 0;i<arr.length;i++){ if(arr[i] < middle){ left.push(arr[i]); }else{ right.push(arr[i]); } } //4. Combination return quick(left).concat(middle,quick(right)); } var arr = [2, 7, 1, 5, 4, 6, 8] console.log(quick(arr));;
5. Anti shake and throttling
-
Function: used for processing performance optimization
5.1 debounce
-
Anti shake: trigger once within the specified event, start a timer and delay the execution for a certain time (500ms). If there is another trigger event within 500ms, count again
-
The purpose of anti shake is to trigger high-frequency events once within the specified time
-
Implementation idea: start a timer and the event will be delayed for a certain time (30ms). If the whole event is triggered again within this 30ms, the counting will be restarted
-
Basic implementation
//2. Move in div, number + 1 oDiv.onmousemove = debounce(fun,30); function fun() { oDiv.innerText++; } //3. Anti shake: when an event occurs, start the timer and start counting (30). If an event is triggered within the counting range, start counting again var timer; function change() { //Judge that if the timer has been started before, clear the previous timer if (timer) { clearTimeout(timer) } timer = setTimeout(function () { fun(); }, 30); }
-
encapsulation
function debounce(fun,wait) { //fun: event handler, wait: delay event var timer; //Maintain global purity with the help of closed packets return function () { if (timer) { //timer has a value of true. This event has been triggered once. Restart counting clearTimeout(timer); } timer = setTimeout(function () { fun(); }, wait); } }