关于闭包及对象私有变量相关的问题中我的理解

闭包

闭包是一种保护私有变量的机制,如果在函数中声明局部变量,该变量会随着函数的完成而销毁,闭包可以使函数内部的变量不被销毁
ES6之前js是没有块级作用域的,只有全局和函数作用域,闭包可以解决因没有块级作用域而出现的问题

1
2
3
4
5
6
7
8
9
10
11
// 这里只说明他的保护私有变量的能力
const add = (function () {
let count = 0
return function () {
return count++
}
})()

add() // count = 1
add() // count = 2
add() // count = 3

在上面代码中add是一个返回一个匿名函数的立即执行函数,它返回的函数中包含有立即执行函数的私有变量count,这样就形成了一个闭包,count变量并不会因为函数的执行而销毁,反而一直存在内存中.
闭包能保护私有变量,但私有变量多了也会吃内存,日常代码中闭包还是很常见的,理解了就行。

对象私有属性

创建对象的私有属性是有必要的,可以使用闭包的形式生成私有属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function Private(name,age) {
let _weight = 'private'
let _name=name
let _age=age
return {

getName: () => {
console.log('Name: ' + _name)
},
getAge: () => {
console.log('Age: ' + _age)
},
setAge: (nAge) => {
_age = nAge
},
init: function () {
this.getName()
this.getAge()
}
}
}
let private = new Private('Tony',30)
private.getAge()
// Age: 30
private.setAge(18)
private.getAge()
// Age: 18
console.log(private._weight)
// undefined
private.init()
// Name: Tony
// Age: 18

在上面的代码中,想要读写Private中的变量只能通过放出开的接口才可以,这样便形成了对象的私有属性
init接口的this指向的便是执行时调用接口的实例对象private,该对象在此处只有构造函数放出来的公开接口,对象的私有属性便被实现出来了。