File tree Expand file tree Collapse file tree 3 files changed +73
-0
lines changed
literals-and-constructors Expand file tree Collapse file tree 3 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
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 >
Original file line number Diff line number Diff line change
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 >
Original file line number Diff line number Diff line change
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 >
You can’t perform that action at this time.
0 commit comments