-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
hoisting.html
42 lines (38 loc) · 1.23 KB
/
hoisting.html
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
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Hoisting
* Description: var statements anywhere in a function act as if the variables were declared at the top of the function
*/
// antipattern
wontchange = "global"; // global variable
willchange = "global"; // global variable
function func_bad() {
alert(wontchange); // "global"
alert(willchange); // "undefined" due to the var below
var willchange = "local"; // This rescopes willchange inside this function
alert(willchange); // "local"
}
func_bad();
// the preceding code snippet will behave as if it were implemented like so:
wontchange = "global"; // global variable
willchange = "global"; // global variable
function func() {
// This still rescopes, but it is a lot more explicit
var willchange; // same as -> var willchange = undefined;
alert(wontchange); // "global"
alert(willchange); // "undefined"
willchange = "local";
alert(willchange); // "local"
}
func();
// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
</script>
</body>
</html>