Format of code development - pay attention to conflicts and dependencies
There are many ways to write a project, such as modular development, namespace, closure Closure is actually a kind of writing
Closure: it is a function structure unique to JavaScript (a nested use of functions)
The formation of closures is closely related to the scope of variables and the life cycle of variables. The scope of variables refers to the effective range of variables. The lifetime of a global variable is permanent unless we actively destroy it. For the local variables declared with var keyword in the function, when the function exits, these local variables lose their value, and they will be destroyed with the end of the function call:
Let's talk about the scope chain:
When a function is declared, the local scope is wrapped up level by level, which is the scope chain.
There is an internal attribute of [[scope]] in the function. When the function is created, there will be global objects; when the function is executed, there will be active objects. Why can't the object in the function be obtained outside the function? Because the function is finished, the active object will destroy itself
Three conditions of closure formation
- Function nesting
- Inner function uses variables or parameters of outer function
- Inner function is returned to external call (inner function as return value)
The function of closure
- Isolate scope to avoid scope pollution
- Protect variables with shared meaning to provide relevant operation interface for variables
Disadvantages of closures
- Using closures in inner space will cause stack overflow
- Too complex to use
How to destroy a closure?
null the closure function to destroy the closure
example:
function fn() { var num = 100; function fn2() { // Because inner functions use variables of outer functions // And the inner function is returned to the outer // Cause local variable reference not to be released (local variable not destroyed) // It's always in the inner layer num += 50; console.log(num); } return fn2; } var fn2 = fn(); fn2();//Printing results 150 fn2();//Print result 200
Note: self executing function is not a closure, but self executing function can achieve the effect of closure, and it can also be written as a closure
Application of closure function:
What is high frequency event?
High frequency event refers to the event with high trigger frequency
For example, oninput,onkeypress,onscroll,resize and other events are triggered very frequently
High frequency event performance optimization function throttling
Core idea: in the event of continuous triggering, our function can only be executed once in a certain period of time.
It will take two hours
First time: last execution time;
Second time: interval time
Current time - last execution time > = 2000ms
<!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> #box { width: 300px; height: 300px; background-color: red; } </style> </head> <body> <div id="box"></div> <script> window.onload=function(){ function fn(callback,wait){ let prev=0;// prev is used to record the last execution time return function(){ let args=arguments;//parameter let now=Date.now();//Get current time if(now-prev>=wait){ callback.apply(this,args);//Modify this point, pass in parameter prev=now;// Record the current time as the last execution time } } } let box=document.getElementById('box'); box.addEventListener('mousemove',fn(function(ev){ console.log('Executed move'); console.log(ev); },2000)); } </script> </body> </html>
High frequency event performance optimization function anti shake
For example, we are very familiar with the Lenovo query function of search engine. It is a data request that occurs at the same time as the user types.
However, the frequency of triggering keyboard events is calculated by letters, not by Chinese characters or words. If every letter you type triggers a data request, it is very inefficient. In this case, it is necessary to reduce the frequency of this operation to ensure that the core code is only executed once in a certain period of time. In this way, when the core code block is heavy, our performance will be greatly improved.
Core idea: it means that the event can only be executed once in n seconds after the trigger time. If the event is triggered again in n seconds, the time will be recalculated
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="text" id="search"> <script> window.onload=function(){ //Anti shake function fn(callback,wait){ let timer=null; // Record the id of the timer return function(){ let args=arguments; if(timer) clearTimeout(timer); timer=setTimeout(function(){ callback.apply(this,args); }.bind(this),wait); } } let search=document.getElementById('search'); search.addEventListener('input',fn(function(){ let script=document.createElement('script'); script.src="https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=32095,1422,31326,21125,31069,31253,32045,30823,26350&wd="+this.value+"&req=2&csor=3&pwd=12&cb=callBack&_=1592456567512"; document.body.appendChild(script); document.body.removeChild(script); },2000)); } function callBack(data){ console.log(data); } </script> </body> </html>