JavaScript Patterns 5.7 Object Constants
2024-08-27 20:51:55
Principle
- Make variables shouldn't be changed stand out using all caps.
- Add constants as static properties to the constructor function.
// constructor var Widget = function () { // implementation... }; // constants Widget.MAX_HEIGHT = 320; Widget.MAX_WIDTH = 480;
- General-purpose constant object
set(name, value) // To define a new constant
isDefined(name) // To check whether a constant exists
get(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 defined constant.isDefined("maxwidth"); // false // define constant.set("maxwidth", 480); // true // check again constant.isDefined("maxwidth"); // true // attempt to redefine constant.set("maxwidth", 320); // false // is the value still intact? constant.get("maxwidth"); //
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
最新文章
- 从世界坐标转换成ui的rect坐标的方法
- 关于HttpURLConnection.setFollowRedirects
- win32自绘按钮,使用GDI+(三)
- Adb connection Error:远程主机强迫关闭了一个现有的连接
- cf 61 E. Enemy is weak 离散化+树状数组
- 济南学习 Day 5 T1 pm
- 升级iOS10后SearchController焦点无法获取的问题
- Extended ComboBox添加图标
- 【HDOJ】1483 Automatic Correction of Misspellings
- OC可变參数的函数实现va_start、va_end、va_list的使用
- HashMap 的遍历key与value的方法
- Equals 和==
- sqlmap命令
- Mybatis源码之Statement处理器PreparedStatementHandler(五)
- 找出 Xcode 编译C/C++过程文件及生成文件
- 你不知道的JavaScript(1)LHS查询和RHS查询
- tomcat多实例的端口设置
- codeforces-1080C
- flask之flask_sqlalchemy
- OVF3为订单原因分配成本中心时报错“成本中心未定义”,消息号:VT806