File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed
Expand file tree Collapse file tree 1 file changed +61
-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: Object Constants
10+ Description: an implementation of a contant object provides set, inDefined and get methods
11+ */
12+
13+ var constant = ( function ( ) {
14+ var constants = { } ,
15+ ownProp = Object . prototype . hasOwnProperty ,
16+ allowed = {
17+ string : 1 ,
18+ number : 1 ,
19+ boolean : 1
20+ } ,
21+ prefix = ( Math . random ( ) + "_" ) . slice ( 2 ) ;
22+ return {
23+ set : function ( name , value ) {
24+ if ( this . isDefined ( name ) ) {
25+ return false ;
26+ }
27+ if ( ! ownProp . call ( allowed , typeof value ) ) {
28+ return false ;
29+ }
30+ contants [ prefix + name ] = value ;
31+ return true ;
32+ } ,
33+ isDefined : function ( name ) {
34+ return ownProp . call ( constants , prefix + name ) ;
35+ } ,
36+ get : function ( name ) {
37+ if ( this . isDefined ( name ) ) {
38+ return constans [ prefix + name ] ;
39+ }
40+ return null ;
41+ }
42+ } ;
43+ } ( ) ) ;
44+
45+ // check if defined
46+ constant . isDefined ( "maxwidth" ) ; // false
47+
48+ // define
49+ constant . set ( "maxwidth" , 480 ) ; // true
50+
51+ // check again
52+ constant . isDefined ( "maxwidth" ) ; // true
53+
54+ // attempt to redefine
55+ constant . set ( "maxwidth" , 320 ) ; // false
56+
57+ // is the value still intact?
58+ constant . get ( "maxwidth" ) ; // 480
59+ </ script >
60+ </ body >
61+ </ html >
You can’t perform that action at this time.
0 commit comments