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)

JavaScript Patterns 5.7 Object Constants

时间: 2024-11-10 21:54:03

JavaScript Patterns 5.7 Object Constants的相关文章

JavaScript Patterns 5.4 Module Pattern

MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties array_string = "[object Array]", ops = Object.prototype.toStr

JavaScript Patterns 3.7 Primitive Wrappers

Primitive value types: number, string, boolean, null, and undefined. // a primitive number var n = 100; console.log(typeof n); // "number" // a Number object var nobj = new Number(100); console.log(typeof nobj); // "object"  One reason

JavaScript Patterns 7.1 Singleton

7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. This means that the second time you use the same class to create a new object, you should get the same object that was created the first time. var obj =

JavaScript Patterns 2.12 Writing API Docs

Free and open source tools for doc generation: the JSDoc Toolkit (http://code.google.com/p/jsdoc-toolkit/) and YUIDoc (http://yuilibrary.com/projects/yuidoc). Process of generating API documentation ? Writing specially formatted code blocks ? Running

JavaScript Patterns 2.2 - Minimizing Globals

Access a global variable in a browser environment: myglobal = "hello"; // antipattern console.log(myglobal); // "hello" console.log(window.myglobal); // "hello" console.log(window["myglobal"]); // "hello"

JavaScript Patterns 3.6 Regular Expression Literal

1. Using the new RegExp() constructor // constructor var re = new RegExp("\\\\", "gm"); 2. Using the regular expression literal // regular expression literal var re = /\\/gm;  when using the RegExp()constructor, you also need to escape

JavaScript Patterns 2.10 Naming Conventions

1. Capitalizing Constructors var adam = new Person(); 2. Separating Words camel case - type the words in lowercase, only capitalizing the first letter in each word. upper camel case, as in  MyConstructor(), lower  camel  case,  as  in  myFunction(),

JavaScript Patterns 6.3 Klass

Commonalities • There’s a convention on how to name a method, which is to be considered the constructor of the class. • Classes inherit from other classes. • There’s access to the parent class (superclass) from within the child class. The function ta

JavaScript Patterns 5.3 Private Properties and Methods

All object members are public in JavaScript. var myobj = { myprop : 1, getProp : function() { return this.myprop; } }; console.log(myobj.myprop); // `myprop` is publicly accessible console.log(myobj.getProp()); // getProp() is public too The same is