zoukankan      html  css  js  c++  java
  • JavaScript Patterns 5.7 Object Constants

    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"); // 480

    References: 

    JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

  • 相关阅读:
    清北学堂总结(未完待续。。。。。。。)
    洛谷p3372 线段树模版
    SPFA模版
    线段树 洛谷 p1531 I hate it(I hate it too)
    01 背包找装满方案数 洛谷 p1164 小a点菜
    01 找最大剩余体积 洛谷1049 装箱问题
    洛谷 p1880 石子合并 区间dp
    石子合并 最大值
    清北学堂入学测试d
    HTML 标记 3 —— 框架
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Object-Constants.html
Copyright © 2011-2022 走看看