What are closures?
A closure is a function that can access variables in the outer function scope.
The characteristics of a closure:
1. The variables accessed by the closure will always be kept in the computer memory, which may cause memory leaks.
2. The closure can realize the privatization of variables
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
</body>
<script>
const btns = document.querySelectorAll('button')
// for (let i = 0; i < buttons.length; i++) {
// buttons[i].onclick = function () {
// console.log(i);
// }
// }
for (var i = 0; i < btns.length; i++) {
//btns[i].onmouseup = (function () {})()// 一执行就会立即调用函数
btns[i].onmouseup = (function () {
return function (i) {
console.log(i);
} //该内层函数是return出来的,要访问外层函数的i变量,
//这个i变量就需要从外部传进去,即调用的时候从末尾的()给传进去,
//传到function的()里,此时内层函数就可以访问到外层函数的i变量
})(i)
}