亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JS閉包原理及其使用場(chǎng)景解析

 更新時(shí)間:2020年12月03日 09:31:07   作者:愛折騰的王先生  
這篇文章主要介紹了JS閉包原理及其使用場(chǎng)景解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

閉包定義

可以通過內(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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論