forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object-constants.html
61 lines (55 loc) · 1.39 KB
/
object-constants.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: Object Constants
Description: an implementation of a constant object provides set, inDefined and get methods
*/
var constant = (function () {
var constants = {},
ownProp = Object.prototype.hasOwnProperty,
allowed = {
string:1,
number:1,
boolean:1
},
prefix = (Math.random() + "_").slice(2);
return {
set:function (name, value) {
if (this.isDefined(name)) {
return false;
}
if (!ownProp.call(allowed, typeof value)) {
return false;
}
constants[prefix + name] = value;
return true;
},
isDefined:function (name) {
return ownProp.call(constants, prefix + name);
},
get:function (name) {
if (this.isDefined(name)) {
return constants[prefix + name];
}
return null;
}
};
}());
// check if defined
console.log(constant.isDefined("maxwidth")); // false
// define
console.log(constant.set("maxwidth", 480)); // true
// check again
console.log(constant.isDefined("maxwidth")); // true
// attempt to redefine
console.log(constant.set("maxwidth", 320)); // false
// is the value still intact?
console.log(constant.get("maxwidth")); // 480
</script>
</body>
</html>