闭包
- 1、概念
- 2、闭包应用
- 防抖&节流
1、概念
闭包:就是能够读取其他函数内部变量的函数。
function fn1() {const num = 100;return function(num1) {return num + num1; // 该函数 使用了 父作用域里面的 num,所以被称为闭包}
}const sumFn = fn1();
fn1 = null;
const sum = sumFn(10);// 110,num 会常驻内存,不随 fn1 销毁而销毁;sumFn 被销毁时,num 才会被释放
console.log(sum);
2、闭包应用
闭包应用:使用闭包主要是为了设计私有变量与方法,避免变量污染,防抖与节流。
闭包缺点:常驻内存,增大内存使用量,使用不当易造成内存泄漏,影响性能。
防抖&节流
// 防抖 - n 秒后再执行该事件,若在 n 秒内被重复触发,则重新计时
function debounce(func, wait) {let timeout;return function () {let self = this;let args = arguments;if (timeout) clearTimeout(timeout);timeout = setTimeout(function () {func.apply(self, args);}, wait);}
}// 节流 - n 秒内只运行一次
function throttled(func, wait) {let oldTime = new Date();let timer = null;return function () {let curTime = new Date();let remain = wait - (curTime - oldTime);let self = this;let args = arguments;clearTimeout(timer);if (remain <= 0) {func.apply(self, args);oldTime = new Date();} else {timer = setTimeout(func, remain);}}
}debounce(() => {console.log(123);
}, 1000);