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: Public Static Members
10+ Description: accessible outside the constructor
11+ */
12+
13+ // Public Static Members
14+
15+ // counstructor
16+ var Gadget = function ( ) { } ;
17+
18+ // a static method
19+ Gadget . isShiny = function ( ) {
20+ return "you bet" ;
21+ } ;
22+
23+ // a normal method added to the prototype
24+ Gadget . prototype . setPrice = function ( price ) {
25+ this . price = price ;
26+ } ;
27+
28+ // calling a static method
29+ console . log ( Gadget . isShiny ( ) ) ; // "you bet"
30+
31+ // creating an instance and calling a method
32+ var iphone = new Gadget ( ) ;
33+ iphone . setPrice ( 500 ) ;
34+
35+ console . log ( typeof Gadget . setPrice ) ; // "undefined"
36+ console . log ( typeof iphone . isShiny ) ; // "undefined"
37+
38+ Gadget . prototype . isShiny = Gadget . isShiny ;
39+ console . log ( iphone . isShiny ( ) ) ; // "you bet"
40+
41+
42+ // constructor
43+ var Gadget = function ( price ) {
44+ this . price = price ;
45+ } ;
46+
47+ // a static method
48+ Gadget . isShiny = function ( ) {
49+
50+ // this always works
51+ var msg = "you bet" ;
52+
53+ if ( this instanceof Gadget ) {
54+ // this only works if called non-statically
55+ msg += ", it costs $" + this . price + '!' ;
56+ }
57+
58+ return msg ;
59+ } ;
60+
61+ // a normal method added to the prototype
62+ Gadget . prototype . isShiny = function ( ) {
63+ return Gadget . isShiny . call ( this ) ;
64+ } ;
65+
66+ console . log ( Gadget . isShiny ( ) ) ; // "you bet"
67+
68+ var a = new Gadget ( '499.99' ) ;
69+ console . log ( a . isShiny ( ) ) ; // "you bet, it costs $499.99!"
70+
71+
72+
73+ </ script >
74+ </ body >
75+ </ html >
0 commit comments