老师这里可以看成闭包吗?
来源:6-3 什么是闭包?闭包会用在哪里?

weixin_慕丝2377090
2021-12-13
这个代码是老师设计模式那门课里面的:
在Class里面(Class 是function的语法糖)定义返回了 一个out()函数,这个函数里面有个自由变量cartList,就相当于形成了闭包。所以这里不去清空cartLis就会有内存泄露问题。
老师这样理解对嘛?
因为之前被面试官问到了闭包产生内存泄露的问题,没有想出例子来,不知道我什么理解对不对。
// 停车场
class Park {
constructor(floors) {
this.floors = floors || []
this.camera = new Camera()
this.screen = new Screen()
this.carList = {}
}
in(car) {
// 获取摄像头的信息:号码 时间
const info = this.camera.shot(car)
// 停到某个车位
const i = parseInt(Math.random() * 100 % 100)
const place = this.floors[0].places[i]
place.in()
info.place = place
// 记录信息
this.carList[car.num] = info
}
out(car) {
// 获取信息
const info = this.carList[car.num]
const place = info.place
place.out()
// 显示时间
this.screen.show(car, info.inTime)
// 删除信息存储
delete this.carList[car.num]
}
emptyNum() {
return this.floors.map(floor => {
return `${floor.index} 层还有 ${floor.emptyPlaceNum()} 个车位`
}).join('\n')
}
}
写回答
1回答
-
双越
2021-12-14
没懂你的意思。
你给出的代码,并没有“返回 out 函数”,而是一个 class 的 method 。out 函数里也没有“自由变量 cartList”,而是 this.cartList 这并不是自由变量。
00
相似问题