Principle of JS Closure and Analysis of Its Application Scenario
- 2021-10-11 17:39:55
- OfStack
Closure definition
The combination of scopes that can be accessed by inner functions is called closures.
Closure usage scenarios
Using closures to implement anti-shake
function debounce(callback, time) {
var timer;
return function () {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
callback()
}, time)
}
}<br data-filtered="filtered"><br data-filtered="filtered">window.onresize = debounce(() => {console.log(666)},500)
Using closures to design singleton patterns
class Car{
constructor(color){
this.color = color
}
}
var proxy = (function createCar() {
var instance;
return function (color) {
if (!instance) {
instance = new Car(color)
}
return instance
}
})()
var car = proxy('white')
Using closure traversal to get index values (old problem)
for (var i = 0; i < 10; i++) {
setTimeout(function(){console.log(i)},0) //10 A 10
}
for (var i = 0; i < 10; i++) {
(function(j){
setTimeout(function(){console.log(j)},0) // 0 - 9
})(i)
}
Closure performance
Because closures cause variables in outer function scope to be kept in memory without being recycled, misuse of closures can cause performance problems, keep in mind.