Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f97ef72

Browse files
committed
added literals-and-constructors
1 parent 9b9a243 commit f97ef72

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed
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: Array literal
10+
Description: use array literal notation to avoid potential errors when creating dynamic arrays at runtime
11+
*/
12+
13+
// antipattern
14+
var a = new Array();
15+
16+
// preferred
17+
var a = [];
18+
19+
</script>
20+
</body>
21+
</html>
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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: Enforcing new
10+
Description: when you forget `new`, `this` inside the constructor will point to the global object
11+
*/
12+
13+
// constructor
14+
function Waffle() {
15+
this.tastes = "yummy";
16+
}
17+
18+
// antipattern
19+
// forgotten `new`
20+
var good_morning = Waffle();
21+
console.log(typeof good_morning); // "undefined"
22+
console.log(window.tastes); // "yummy"
23+
24+
// preferred
25+
var good_morning = new Waffle();
26+
console.log(typeof good_morning); // "object"
27+
console.log(good_morning.tastes); // "yummy"
28+
</script>
29+
</body>
30+
</html>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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: Object literal
10+
Description: use the simpler and reliable object literal instead of new Object();
11+
*/
12+
13+
// antipattern
14+
var car = new Object();
15+
car.goes = "far";
16+
17+
// preferred
18+
var car = {goes: "far"};
19+
20+
</script>
21+
</body>
22+
</html>

0 commit comments

Comments
 (0)