JavaScript的闭包
2020-11-22 本文已影响0人
云凡的云凡
当内部函数被返回到外部并保存时,一定会产生闭包,闭包会产生,原来的作用域不能释放,过渡的闭包可能会导致内存泄漏,或加载过慢。
// 闭包做数据缓存
function test() {
var n = 100;
function add() {
n++
console.log(n);
}
function reduce() {
n--;
console.log(n);
}
return [add, reduce]
}
var arr = test()
arr[0]()//101
arr[1]()//100
arr[1]()//99
arr[1]()//98
arr[1]()//97
arr[1]()//96
增删改查
function breadMgr(num) {
// var breadNum = num || 10
var breadNum = arguments[0] || 10
function storage() {
breadNum += 10
console.log(breadNum);
}
function sale() {
breadNum--;
console.log(breadNum);
}
return [storage, sale]
}
var breadMgr = breadMgr(50)
breadMgr[0]()//60
breadMgr[1]()//59
function rechang(name) {
var opt = {
showThing: function () {
console.log("hello " + name);
}
}
return opt
}
var things = rechang("mary")
things.showThing()//hello mary
function test() {
for (var i = 0; i < 10; i++) {
(function () {
document.writeln(i + ' ')
})()
}
}
test()//0 1 2 3 4 5 6 7 8 9
function test() {
for (var i = 0; i < 10; i++) {
console.log(i);
}
}
test()//0 1 2 3 4 5 6 7 8 9
var a = []
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
}
}
a[5]()//10
var b = []
for (let i = 0; i < 10; i++) {
b[i] = function () {
console.log(i);
}
}
b[5]()//5
形成闭包
<script>
// 把 add 方法返回出去赋值给了 adds 变量,然后adds变量成了一个新的函数,
// 这个函数其实就是test里面那个add方法,里面的add方法拽着test的AO,
// test的AO有num,所以可以任意修改
function test() {
var num = 0
function add() {
console.log(++num);
}
return add
}
var adds = test()
adds()//1
</script>
闭包缓存数据1
function myClass() {
var student = []
var operations = {
join: function (name) {
student.push(name)
console.log(student);
document.writeln(student + `<br>`)
},
leave: function (name) {
for (var i = 0; i < student.length; i++) {
var item = student[i] //优化for循环性能的方法
if (item === name) {
student.splice(i, 1)
}
}
console.log(student + "123");
document.writeln(student + `<br>`)
}
}
return operations
}
var opt = myClass()
opt.join('张三')
opt.join('李四')
opt.join('王五')
opt.leave('李四')
闭包缓存数据2
function myClass() {
var student = []
var operations = {
join: function (name) {
student.push(name)
console.log(student);
document.writeln(student + `<br>`)
},
leave: function (name) {
// for (var i = 0; i < student.length; i++) {
// var item = student[i] //优化for循环性能的方法
// if (item === name) {
// student.splice(i, 1)
// }
// }
var idx = student.indexOf(name)
if (idx !== -1) {
student.splice(idx, 1)
}
console.log(student + "123");
document.writeln(student + `<br>`)
}
}
return operations
}
var opt = myClass()
opt.join('张三')
opt.join('李四')
opt.join('王五')
opt.leave('李四')