-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtest_scope.js
78 lines (59 loc) · 1.63 KB
/
test_scope.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
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
// test_scope.js
// -------------
var assert = console.assert;
// ------------------------------------------------------------------
// Function Scope
// ------------------------------------------------------------------
var x = 1;
(function() {
var y = 2;
(function() {
var z = 3;
(function() {
// Does not throw a ReferenceError because it is hoisted.
assert(toBeHoisted == undefined);
// And a sanity check that it would fail otherwise.
assert(typeof notARealVariable == 'undefined');
// Nested scopes can access outer scope vars
assert(x == 1);
assert(y == 2);
assert(z == 3);
// Nested scopes can set outer scope vars
x = 5;
var toBeHoisted = 42;
(function() {
// Variable shadowing
var y = 9;
})();
})();
})();
// This scope's 'y' is still 2
assert(y == 2);
})();
// Inner func changed our x
assert(x == 5);
// 'z' was local to 2nd-level func.
assert(this.z === undefined);
// ------------------------------------------------------------------
// Tricks (adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting)
// ------------------------------------------------------------------
// foo is hoisted and becomes undefined within the function scope,
// foo then becomes 10 after the assignment.
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
return foo;
}
assert(bar() === 10);
// a is shadowed within the function scope by the function declaration.
// The inner a (not the outer scope a) is then reassigned to 10.
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
assert(a === 1);