Repository navigation
Expand file tree
/
Copy pathclosures.html
More file actions
112 lines (80 loc) · 2.67 KB
/
Copy pathclosures.html
File metadata and controls
112 lines (80 loc) · 2.67 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<script type="text/javascript">
//'use strict';
//闭包是阻止垃圾回收器将变量从内存中移除的方法, 使得在创建变量的执行环境的外面能够访问到该变量
//JavaScript 实现了自动释放内存的系统, 即垃圾回收器, 简称 gc (garbage collector)
//当函数执行完毕的时候, gc 会将函数中所有创建的东西从内存中清理
//但是如果函数执行完毕后, 依旧有函数可以访问这个变量, 那么这个变量就不会被释放, 这就是 闭包
//闭包通常的使用场景 和 this 对象有关, 比如下面这个场景 :
var name = "Here is Global";
var local = {
name: "Here is Local",
getNameFunction: function () {
var that = this;
return function () {
console.log(that.name);
console.log(this.name);
}
}
};
//local.getNameFunction()();
// 运行结果:
// Here is Local
// Here is Global
// 严格模式下运行结果:
// Here is Local
// Uncaught TypeError: Cannot read property 'name' of undefined
// 回调函数皆闭包
// 闭包的写法
// One
(function () {
var name = "local";
return function () {
return this.name;
}
})();
// Two
var mod1 = (function () {
return {
func1: function () {
//do something
console.log("func1");
},
func2: function () {
//do something
},
// ...
};
})();
//mod1.func1(); // "func1"
// Three
function funcA() {
function funcB() {
//do something
console.log("Hello Closure!");
}
return funcB;
}
var testFunc = funcA();
//testFunc(); //Hello Closure!
// Four 将function作为值返回, 并且包含当前环境下的变量
var Circle = function () {
var obj = new Object();
obj.PI = 3.14159;
obj.area = function (r) {
return this.PI * r * r;
}
return obj;
}
var c = new Circle();
//console.log(c.area(1.0)); // "3.14159"
</script>
</body>
</html>