JS閉包原理及其使用場(chǎng)景解析
閉包定義
可以通過內(nèi)層函數(shù)訪問外層函數(shù)的作用域的組合叫做閉包。
閉包使用場(chǎng)景
使用閉包來實(shí)現(xiàn)防抖
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)
使用閉包設(shè)計(jì)單例模式
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’)
使用閉包遍歷取索引值(古老的問題)
for (var i = 0; i < 10; i++) { setTimeout(function(){console.log(i)},0) //10個(gè)10}for (var i = 0; i < 10; i++) { (function(j){ setTimeout(function(){console.log(j)},0) // 0 - 9 })(i)}
閉包性能
因?yàn)殚]包會(huì)使外層函數(shù)作用域中的變量被保存在內(nèi)存中不被回收,所以如果濫用閉包就會(huì)導(dǎo)致性能問題,謹(jǐn)記。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python 的 __str__ 和 __repr__ 方法對(duì)比2. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法3. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)4. IntelliJ IDEA設(shè)置背景圖片的方法步驟5. docker /var/lib/docker/aufs/mnt 目錄清理方法6. Python TestSuite生成測(cè)試報(bào)告過程解析7. 學(xué)python最電腦配置有要求么8. JAMon(Java Application Monitor)備忘記9. Python Scrapy多頁數(shù)據(jù)爬取實(shí)現(xiàn)過程解析10. Python OpenCV去除字母后面的雜線操作
