forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingle-var-pattern.html
55 lines (48 loc) · 1.3 KB
/
single-var-pattern.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
43
44
45
46
47
48
49
50
51
52
53
54
55
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Single var Pattern
Description: use one var statement and declare multiple variables
*/
/* Benefits:
* 1. Provides a single place to look for all the local variables needed by the function
* 2. Prevents logical errors when a variable is used before it's defined
* 3. Helps you remember to declare variables and therefore minimize globals
* 4. Is less code (to type and to transfer over the wire)
*/
function func() {
var a = 1
, b = 2
, sum = a + b
, myobject = {}
, i
, j;
// function body...
}
function updateElement() {
var el = document.getElementById("result")
, style = el.style;
// do something with el and style...
}
// Preferred way
// Move commas BEFORE vars
// You'll not forget to add one when adding variable to the end of list
function func() {
var a = 1
, b = 2
, sum = a + b
, myobject = {}
, i
, j;
// function body...
}
// References
// http://net.tutsplus.com/tutorials/javascript-ajax/the-essentials-of-writing-high-quality-javascript/
</script>
</body>
</html>