js0016

使用关键字var时 该变量时在距离最近的函数内部或是在全局词法环境中定义的

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
<!DOCTYPE html>
<html>
<head>
<title>Using the var keyword</title>
<meta charset="utf-8">
<script src="../assert.js"></script>
<link rel="stylesheet" type="text/css" href="../assert.css">
</head>
<body>
<script>
var globalNinja = "Yoshi";

function reportActivity(){
var functionActivity = "jumping";

for(var i = 1; i < 3; i++) {
var forMessage = globalNinja + " " + functionActivity;
assert(forMessage === "Yoshi jumping",
"Yoshi is jumping within the for block");
assert(i, "Current loop counter:" + i);
}

assert(i === 3 && forMessage === "Yoshi jumping",
"Loop variables accessible outside of the loop");
}

// for 循环外部 仍然能够访问for循环中定义的变量

reportActivity();
assert(typeof functionActivity === "undefined"
&& typeof i === "undefined" && typeof forMessage === "undefined",
"We cannot see function variables outside of a function");
</script>
</body>
</html>