很多刚接触闭包的人可能会对闭包产生误解:
- 认为内部函数必须要被return,实际上return内部函数只是为了方便使用。在本文章内就使用了window.xxx的方式将函数暴露到外部(没有使用return),外部则可以通过使用我暴露的方法来改变blood的值。而不能直接修改blood,起到了隐藏变量的作用。隐藏变量即你可以间接使用变量,但不能直接修改变量。
- 不清楚闭包到底何时产生的,认为内部函数执行时,才产生闭包。实际上当外部函数执行调用时,闭包就产生了。因为存在函数提升的阶段,所以在外部函数内部最顶层的代码就已经对内部函数编译执行(定义阶段),这时候blood为undefined,闭包就已经产生了。
function father() {
var blood = 30
//increaseBlood() 增加血量
window.increaseBlood = function increaseBlood() {
blood++
console.log('increaseBlood:' + '你还有' + blood + '血量');
}
//decreaseBlood() 减少血量
window.decreaseBlood = function decreaseBlood() {
blood--
console.log('decreaseBlood:' + '你还有' + blood + '血量');
}
//queryBlood() 查询血量
window.queryBlood = function queryBlood() {
console.log('queryBlood:' + '你还有' + blood + '血量');
}
console.log('father:' + '你还有' + blood + '血量');
}
father()
window.increaseBlood()
//解除对increaseBlood的引用,increaseBlood引用的increaseBlood函数变为垃圾对象
window.increaseBlood = null
window.queryBlood()
window.decreaseBlood()
window.queryBlood()