-
Notifications
You must be signed in to change notification settings - Fork 1
/
闭包设计.html
66 lines (58 loc) · 1.06 KB
/
闭包设计.html
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script>
/**
* 闭包的两种
*/
var createPet = function(name){
var sex;
return {
setName : function(newName){
name = newName;
},
getName : function(){
return name;
},
getSex : function(){
return sex;
},
setSex : function(newSex){
if(typeof newSex == 'string' && newSex.toLowerCase() == 'male'|| newSex.toLowerCase() == 'female'){
sex = newSex;
}
}
};
}
var getCode = function(){
var code = "<h1>闭包测试</g1>";
return function(){
return code;
}
}
//测试闭包
var body = document.querySelector('body');
var code = getCode();
var element = document.createElement("div");
element.innerHTML = code();
body.appendChild(element);
var pet = createPet('阿黄');
console.log(pet.getName())
pet.setName("吉娃娃")
pet.setSex("male")
console.log(pet.getSex());
console.log(pet.getName());
//错误演示
var errTest = function(name){
return {
test:function(name){
name = name;
}
}
}
</script>
</body>
</html>