-
Notifications
You must be signed in to change notification settings - Fork 213
/
demo.js
53 lines (47 loc) · 1011 Bytes
/
demo.js
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
function g() {
return 'outer';
}
function f(flag) {
var result = [];
function g() {
return 'inner';
}
if(flag) {
result.push(g());
}
result.push(g());
return result;
}
console.log(f(true)); // [ 'inner', 'inner' ]
console.log(f(false)); // [ 'inner' ]
function f1(flag) {
var result = [];
//function g() {
// return 'inner';
//}
if(flag) {
function g() {
return 'inner';
}
result.push(g());
}
result.push(g());
return result;
}
console.log(f1(true)); // [ 'inner', 'inner' ]
// console.log(f1(false)); // g is not a function 产生了局部快作用域
// 下面是比较正确的做法
function f2(flag) {
var result = [];
var g1 = g;
if(flag) {
g1 = function() {
return 'inner';
};
result.push(g1());
}
result.push(g1());
return result;
}
console.log(f2(true)); // [ 'inner', 'inner' ]
console.log(f2(false)); // [ 'outer' ]