闭包

1.概念

能够读取其它函数作用域里变量的函数

2.应用

// 2.1累加器
function hd(){
       let n = 0
       return ()=>{
           console.log(++n)
       }
}
const sum = hd()
sum()
sum()
// 2.2类
function Hd(){
     this.n = 1
     this.sum = function (){
console.log(++this.n)
     }
 }
const a = new Hd()
a.sum()
a.sum()
// 2.3块级作用域
 for(var i = 0;i<5;i++){
       ((i)=>{
           setTimeout(()=>{
               console.log(i)
           },1000)
       })(i)
}

const arr = []
for(var j = 0;j<5;j++){
       ((i)=>{
           arr.push(function (){
               console.log(i)
           })
       })(j)
 }
arr.forEach( v => v())
// demo 获取区间
let arr = [1,2,3,4,5,8,56,76,700,66,1,2,4,6,55,3,3]
function between(a,b){
      return (v) => {
          return v >= a && v <= b
      }
}
console.log(arr.filter(between(10,100)))
 // demo 按钮移动
const btns =document.getElementsByTagName('button')
Array.from(btns).forEach(v => {
       let bind = false
       v.addEventListener('click',function(e){
           if(!bind){
               let left = 1
               bind = setInterval(() => {
                   left = left + 1
                   v.style.left = left + 'px'
               },200)
           }
       })
})
// demo 排序
const data = [
       {
           title:'花生奶',
           price:50,
           count:5
       },
       {
           title:'牛仔裤',
           price:200,
           count:2
       },
       {
           title:'方便面',
           price:100,
           count:20
       },
       {
           title:'火龙果',
           price:55,
           count:8
       },
]
function order(filed,type='asc'){
       return (a,b) => {
          if(type === 'asc') return a[filed] > b[filed] ? 1 : -1
          else return a[filed] > b[filed] ? -1 : 1
       }
}
console.log(data.sort(order('count','desc')))

3.闭包解决内存泄漏

const div =document.getElementsByTagName('div')
Array.from(btns).forEach(v => {
       const text = v.innerText
       v.addEventListener('click',function(e){
           // console.log(v.innerText)  会造成内存保存v
           console.log(text)
       })
       v = null
})

 4.闭包this遗留问题

let hd = {
      user:'zhangsan',
      get:function (){
           // return function(){
           return () => {
               return this.user
           }
      }
}
const a = hd.get()
console.log(a())

 

posted @ 2021-08-29 11:03  卷叶小树  阅读(32)  评论(0编辑  收藏  举报