闭包的小案例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>闭包小案例</title> </head> <body> <div> <input type="text" id="input"> <button id="search">查询报名</button> <button id="insert">插入</button> <button id="search2">已报名人更新</button> </div> <div id="students"> </div> <script> const inputDom = document.querySelector('#input') const searchDom = document.querySelector('#search') const insertDom = document.querySelector('#insert') const insertDom2 = document.querySelector('#search2') const students = document.querySelector('#students') // 封装变量: 封装一个变量来收集学生姓名 // 收敛权限:只有特定的方法才能操作学生变量 //优点: 不会造成变量污染 //缺点:垃圾回收机制:当变量引用为0 ,会被释放 // 所以闭包的变量不会被垃圾回收机制回收 会内存溢出 var studentsSys = function(){ let list = [] return { search(name){ if(list.includes(name)){ console.log('已报名') return true } console.log('未报名') return false }, insert(name){ console.log(name) list.push(name) }, console(){ console.log(list.toString()) students.innerText = list.toString() } } }() searchDom.onclick=function(){ console.log(inputDom.value) const status = studentsSys.search(inputDom.value) } insertDom.onclick=function(){ const status = studentsSys.insert(inputDom.value) } insertDom2.onclick=function(){ console.log(111) const status = studentsSys.console() } </script> </body> </html>