JS閉包原理及其使用場(chǎng)景解析
閉包定義
可以通過(guò)內(nèi)層函數(shù)訪問(wèn)外層函數(shù)的作用域的組合叫做閉包。
閉包使用場(chǎng)景
使用閉包來(lái)實(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’)
使用閉包遍歷取索引值(古老的問(wèn)題)
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)致性能問(wèn)題,謹(jǐn)記。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python如何批量生成和調(diào)用變量2. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題3. Python基于requests實(shí)現(xiàn)模擬上傳文件4. python利用opencv實(shí)現(xiàn)顏色檢測(cè)5. Python sorted排序方法如何實(shí)現(xiàn)6. Python 中如何使用 virtualenv 管理虛擬環(huán)境7. 通過(guò)CSS數(shù)學(xué)函數(shù)實(shí)現(xiàn)動(dòng)畫(huà)特效8. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車9. ASP.Net Core(C#)創(chuàng)建Web站點(diǎn)的實(shí)現(xiàn)10. Python獲取B站粉絲數(shù)的示例代碼
