JavaScript Patterns 5.7 Object Constants
2014-07-01 23:01 小郝(Kaibo Hao) 阅读(309) 评论(0) 编辑 收藏 举报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"); // 480
References:
JavaScript Patterns - by Stoyan Stefanov (O`Reilly)
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。