Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
62 lines (55 sloc) 1.39 KB
<!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, isDefined 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>