首页 > 代码库 > JavaScript Patterns 5.7 Object Constants
JavaScript Patterns 5.7 Object Constants
Principle
- Make variables shouldn‘t be changed stand out using all caps.
- Add constants as static properties to the constructor function.
// constructorvar Widget = function () { // implementation...};// constantsWidget.MAX_HEIGHT = 320;Widget.MAX_WIDTH = 480;
- General-purpose constant object
set(name, value) // To define a new constantisDefined(name) // To check whether a constant existsget(name) // To get the value of a constant
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; } };}());
Testing the implementation:
// check if definedconstant.isDefined("maxwidth"); // false// defineconstant.set("maxwidth", 480); // true// check againconstant.isDefined("maxwidth"); // true// attempt to redefineconstant.set("maxwidth", 320); // false// is the value still intact?constant.get("maxwidth"); // 480
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。