Skip to content

Commit 7bcb1ac

Browse files
committed
added more literal and constructor patterns
1 parent 144a0d0 commit 7bcb1ac

3 files changed

Lines changed: 97 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
/* Title: Working with JSON
10+
Description: use library from JSON.org or YUI, jQuery library
11+
*/
12+
13+
// an input JSON string
14+
var jstr = '{"mykey": "my value"}';
15+
16+
// antipattern
17+
var data = eval('(' + jstr + ')');
18+
19+
// preferred
20+
// JSON.org library
21+
var data = JSON.parse(jstr);
22+
console.log(data.mykey); // "my value"
23+
24+
</script>
25+
</body>
26+
</html>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
/* Title: Primitive Wrappers
10+
Description: JavaScript has 3 primitive wrapper objects: number, string, boolean
11+
*/
12+
13+
// antipattern
14+
// with wrappers
15+
var s = new String("my string");
16+
var n = new Number(101);
17+
var b = new Boolean(true);
18+
19+
// preferred
20+
// without wrappers
21+
var s = "my string";
22+
var n = 101;
23+
var b = true;
24+
25+
/*
26+
only use primitive wrappers when you want to augment the value and persist state
27+
*/
28+
29+
// primitive string
30+
var greet = "Hello there";
31+
// primitive is converted to an object
32+
// in order to use the split() method
33+
greet.split(' ')[0]; // "Hello"
34+
// attemting to augment a primitive is not an error
35+
greet.smile = true;
36+
// but it doesn't actually work
37+
console.log(typeof greet.smile); // "undefined"
38+
39+
// primitive string
40+
var greet = new String("Hello there");
41+
// primitive is converted to an object
42+
// in order to use the split() method
43+
greet.split(' ')[0]; // "Hello"
44+
// attemting to augment a primitive is not an error
45+
greet.smile = true;
46+
// but it doesn't actually work
47+
console.log(typeof greet.smile); // "boolean"
48+
</script>
49+
</body>
50+
</html>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
/* Title: Regular Expression Literal
10+
Description: the regular expression literal notation is shorter
11+
*/
12+
13+
// antipattern
14+
var re = new RegExp("\\\\", "gm");
15+
16+
// preferred
17+
var re = /\\/gm;
18+
19+
</script>
20+
</body>
21+
</html>

0 commit comments

Comments
 (0)