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+ var obj = {
10+ myprop : 'my value'
11+ } ;
12+
13+ var obj2 = {
14+ myprop : 'my value'
15+ } ;
16+ obj === obj2 ; // false
17+ obj == obj2 ; // false
18+
19+ var uni = new Universe ( ) ;
20+ var uni2 = new Universe ( ) ;
21+ uni === uni2 ; // true
22+
23+ function Universe ( ) {
24+
25+ // do we have an existing instance?
26+ if ( typeof Universe . instance === "object" ) {
27+ return Universe . instance ;
28+ }
29+
30+ // proceed as normal
31+ this . start_time = 0 ;
32+ this . bang = "Big" ;
33+
34+ // cache
35+ Universe . instance = this ;
36+
37+ // implicit return:
38+ // return this;
39+ }
40+
41+ // testing
42+ var uni = new Universe ( ) ;
43+ var uni2 = new Universe ( ) ;
44+ uni === uni2 ; // true
45+
46+ /*** Instance in a Closure ***/
47+
48+ function Universe ( ) {
49+
50+ // the cached instance
51+ var instance = this ;
52+
53+ // proceed as normal
54+ this . start_time = 0 ;
55+ this . bang = "Big" ;
56+
57+ // rewrite the contructor
58+ Universe = function ( ) {
59+ return instance ;
60+ } ;
61+ }
62+
63+ function Universe ( ) {
64+
65+ // the cached instance
66+ var instance ;
67+
68+ // rewrite the constructor
69+ Universe = function Universe ( ) {
70+ return instance ;
71+ } ;
72+
73+ // carry over the prototype properties
74+ Universe . prototype = this ;
75+
76+ // the instance
77+ instance = new Universe ( ) ;
78+
79+ // reset the constructor pointer
80+ instance . constructor = Universe ;
81+
82+ // all the functionality
83+ instance . start_time = 0 ;
84+ instance . bang = "Big" ;
85+
86+ return instance ;
87+ }
88+
89+
90+
91+ // testing
92+ var uni = new Universe ( ) ;
93+ var uni2 = new Universe ( ) ;
94+ uni === uni2 ; // true
95+
96+ // adding to the prototype
97+ Universe . prototype . nothing = true ;
98+
99+ var uni = new Universe ( ) ;
100+
101+ // again adding to the prototype
102+ // after the initial object is created
103+ Universe . prototype . everything = true ;
104+
105+ var uni2 = new Universe ( ) ;
106+
107+ // only the original prototype was
108+ // linked to the objects
109+ uni . nothing ; // true
110+ uni2 . nothing ; // true
111+ uni . everything ; // undefined
112+ uni2 . everything ; // undefined
113+
114+ // that sounds right:
115+ uni . constructor . name ; // "Universe"
116+
117+ // but that's odd:
118+ uni . constructor === Universe ; // false
119+
120+ var Universe ;
121+
122+ ( function ( ) {
123+
124+ var instance ;
125+
126+ Universe = function Universe ( ) {
127+
128+ if ( instance ) {
129+ return instance ;
130+ }
131+
132+ instance = this ;
133+
134+ // all the functionality
135+ this . start_time = 0 ;
136+ this . bang = "Big" ;
137+ } ;
138+ } ( ) ) ;
139+ </ script >
140+ </ body >
141+ </ html >
0 commit comments