Principle

  1. Make variables shouldn't be changed stand out using all caps.
  2. Add constants as static properties to the constructor function.
// constructor

var Widget = function () {

    // implementation...

};

// constants

Widget.MAX_HEIGHT = 320;

Widget.MAX_WIDTH = 480;
  1. 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)

最新文章

  1. 从世界坐标转换成ui的rect坐标的方法
  2. 关于HttpURLConnection.setFollowRedirects
  3. win32自绘按钮,使用GDI+(三)
  4. Adb connection Error:远程主机强迫关闭了一个现有的连接
  5. cf 61 E. Enemy is weak 离散化+树状数组
  6. 济南学习 Day 5 T1 pm
  7. 升级iOS10后SearchController焦点无法获取的问题
  8. Extended ComboBox添加图标
  9. 【HDOJ】1483 Automatic Correction of Misspellings
  10. OC可变參数的函数实现va_start、va_end、va_list的使用
  11. HashMap 的遍历key与value的方法
  12. Equals 和==
  13. sqlmap命令
  14. Mybatis源码之Statement处理器PreparedStatementHandler(五)
  15. 找出 Xcode 编译C/C++过程文件及生成文件
  16. 你不知道的JavaScript(1)LHS查询和RHS查询
  17. tomcat多实例的端口设置
  18. codeforces-1080C
  19. flask之flask_sqlalchemy
  20. OVF3为订单原因分配成本中心时报错“成本中心未定义”,消息号:VT806

热门文章

  1. ASP.NET MVC 模块与组件(二)——定制图片验证码
  2. Nlog 记录日志到 sqlite
  3. hibernate 注释说明
  4. python3.4怎么连接mysql pymysql连接mysql数据库
  5. 设置surfaceView的背景为透明
  6. android 密码输入通过复选框实现明文密文显示
  7. PLSQL怎样导出oracle表结构和数据
  8. C++之面向对象的三个基本特征
  9. js获取本机的外网/广域网ip地址
  10. angularjs 指令—— 绑定策略(@、=、&)