The scenario
1. Function anti-shake
For example, to scale the window and trigger the onResize event, we need to do one thing at this time, but we want to only trigger once when we drag, for example
window.onresize = function(){
console.log('onresize')// Only once}Copy the code
Generic methods vs closures
window.onresize = function(){
debounce(fn,1000)
}
var fn = function(){ console.log('fn')
}
var time = ' '
function debounce(fn,timeLong){
if(time){
clearTimeout(time)
time = ' '
}
time =setTimeout(function(){
fn()
},timeLong)
}Copy the code
window.onresize = debounce(fn,500)
function debounce(fn){
var timer = null
return function() {if(timer){// Timer is stored in memory after the first execution and is always the executor until the last one is triggered clearTimeout(timer) timer = null} timer =setTimeout(function(){
fn()
},1000)
}
}
var fn = function(){
console.log('fn')}Copy the code
2. Design singleton patterns using closures
class CreateUser {
constructor(name) {
this.name = name;
this.getName();
}
getName() {
returnthis.name; }} var ProxyMode = (function() {
var instance = null;
return function(name) {
if(! instance) { instance = new CreateUser(name); }returninstance; }}) (); Var a = ProxyMode("aaa");
var b = ProxyMode("bbb"); // Since the singleton mode is instantiated only once, the following instances are equal console.log(a === b); //trueCopy the code
3. Independent attribute for multiple components
If I were to use Echarts now to draw six line graphs on a page, I would need six containers
You need to declare a separate ID for each container element, otherwise it gets messy
constructor(){
this.state = {id: "EchartsLine"+Util.clourse()};
}
componentDidMount() { this.myEChart =echarts.init(document.getElementById(this.state.id)); // different id}Copy the code
<div
id={this.state.id}
className='echarts-line'>
</div>
Copy the code
clourse(){
let clourse = (function(){
var a = 1; return function(){ return a++; } })(this); this.clourse = clourse; } // Use numeric names without fear of tamperingCopy the code
4. Set private variables
Internal attributes can be private in Java, but JS doesn’t have that yet
let _width = Symbol();
class Private {
constructor(s) {
this[_width] = s
}
foo() {
console.log(this[_width])
}
}
var p = new Private("50"); p.foo(); console.log(p[_width]); // You can get itCopy the code
// Assign to the closurelet sque = (function () {
let _width = Symbol();
class Squery {
constructor(s) {
this[_width] = s
}
foo() {
console.log(this[_width])
}
}
return Squery
})();
let ss = new sque(20);
ss.foo();
console.log(ss[_width])Copy the code
5. Get the correct value (old question 😝)
for(var i=0; i<10; i++){setTimeout(function(){console.log(I)//10 10},1000)}Copy the code
How to solve this problem
for(var i=0; i<10; i++){ ((j)=>{setTimeout(function(){
console.log(j)//1-10
},1000)})(i)
}Copy the code
The principle is to declare 10 self-executing functions, save the current value to internal