封装

闭包的特性就是有一个全局变量保存函数中的值,从而访问函数的内部

第一种

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
function student1() {
var privateStore = {

};
this._set = function (obj) {
for (var i in obj) {
privateStore[i] = obj[i];
}
};
this._get = function () {
return privateStore;
};
this.get = function () {
return this._get;
};
this.set = function (obj) {
return this._set;
};

}
var stu1 = new student1();
var set = stu1.set();
set({
name: "张宇",
ex: "男",
age: 18
});
var get = stu1.get();
console.log(stu1);
console.log(get());

第二种

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
function student() {
var privateStore = {

};

function _set(obj) {
for (var i in obj) {
privateStore[i] = obj[i];
}
};

function _get() {
return privateStore;
};
this.get = function () {
return _get;
};
this.set = function (obj) {
return _set;
};
}
var stu = new student();
var set = stu.set();
set({
name: "张宇",
ex: "男",
age: 18
});
var get = stu.get();
console.log(stu);
console.log(get());