Ping-Yen Tsai
May 14, 2014
93

# JavaScript Closure

May 14, 2014

## Transcript

1. JavaScript Closure
Ping-Yen Tsai
1 / 10

2. JavaScript 函式裡還可以宣告函式
f
u
n
c
t
i
o
n f
(
) {
g
(
)
;
f
u
n
c
t
i
o
n g
(
) {
a
l
e
r
t
(
1
)
;
}
}
f
(
)
; /
/ 1
g
(
)
; /
/ R
e
f
e
r
e
n
c
e
E
r
r
o
r
: g i
s n
o
t d
e
f
i
n
e
d
2 / 10

3. 裡面的函示可以存取外面函示的變數
f
(
)
;
f
u
n
c
t
i
o
n f
(
) {
v
a
r c = 0
;
g
(
)
;
a
l
e
r
t
(
c
)
; /
/ 1
g
(
)
;
a
l
e
r
t
(
c
)
; /
/ 2
f
u
n
c
t
i
o
n g
(
) { +
+
c
; }
}
3 / 10

4. Closure = 函式 + 函式外變數
f
u
n
c
t
i
o
n f
(
) {
v
a
r c = 0
;
f
u
n
c
t
i
o
n g
(
) { +
+
c
; }
}
函式與函式外變數生存期間一致
v
a
r h = f
(
)
;
f
u
n
c
t
i
o
n f
(
) {
v
a
r c = 0
;
f
u
n
c
t
i
o
n g
(
) { +
+
c
; }
r
e
t
u
r
n g
;
}
4 / 10

5. Closure Sample
v
a
r h
1 = f
(
)
;
h
2 = f
(
)
;
h
1
(
)
; /
/ 1
h
1
(
)
; /
/ 2
h
2
(
)
; /
/ 1
f
u
n
c
t
i
o
n f
(
) {
v
a
r c = 0
;
f
u
n
c
t
i
o
n g
(
) { a
l
e
r
t
(
+
+
c
)
; }
r
e
t
u
r
n g
;
}
5 / 10

6. Closure Sample
v
a
r h = (
f
u
n
c
t
i
o
n
(
) {
v
a
r c = 0
;
r
e
t
u
r
n f
u
n
c
t
i
o
n
(
) { +
+
c
; }
}
)
(
)
;
6 / 10

7. Global 變數
v
a
r c = 0
;
v
a
r h = f
u
n
c
t
i
o
n
(
) { a
l
e
r
t
(
+
+
c
)
; }
;
h
(
)
; /
/ 1
h
(
)
; /
/ 2
h
(
)
; /
/ 3
Closure
v
a
r h = (
f
u
n
c
t
i
o
n
(
) {
v
a
r c = 0
;
r
e
t
u
r
n f
u
n
c
t
i
o
n
(
) { a
l
e
r
t
(
+
+
c
)
; }
;
}
)
(
)
;
h
(
)
; /
/ 1
h
(
)
; /
/ 2
h
(
)
; /
/ 3
7 / 10

8. 達成近似 Java Class Private Member 效果
8 / 10

9. Google Maps JavaScript API v3 範例
Using closures in event listeners
9 / 10

10. Free variables and bound variables - Wikipedia
10 / 10