标签:style blog http io 使用 java ar strong for
JavaScript中的创建对象的基本方法有字面声明(Object Literal)和构造函数两种,但JavaScript并没有特别的语法来表示如命名空间、模块、包、私有属性、静态属性等等面向对象程序设计中的概 念。为了让JavaScript实现面向对象程序中的高级语义,人们发明了命名空间模式、依赖声明模式,模块模式,以及沙盘模式。
// BEFORE: 5 globals
// Warning: antipattern
// constructors
function Parent() {}
function Child() {}
// a variable
var some_var = 1;
// some objects
var module1 = {};
module1.data = {a: 1, b: 2};
var module2 = {};
// AFTER: 1 global
// global object
var MYAPP = {};
// constructors
MYAPP.Parent = function () {};
MYAPP.Child = function () {};
// a variable
MYAPP.some_var = 1;
// an object container
MYAPP.modules = {};
// nested objects
MYAPP.modules.module1 = {};
MYAPP.modules.module1.data = {a: 1, b: 2};
MYAPP.modules.module2 = {};
// unsafe
var MYAPP = {};
// better
if (typeof MYAPP === "undefined") {
var MYAPP = {};
}
// or shorter
var MYAPP = MYAPP || {};
// using a namespace function
MYAPP.namespace(‘MYAPP.modules.module2‘);
// equivalent to:
// var MYAPP = {
// modules: {
// module2: {}
// }
// };
var MYAPP = MYAPP || {};
MYAPP.namespace = function (ns_string) {
var parts = ns_string.split(‘.‘),
parent = MYAPP,
i;
// strip redundant leading global
if (parts[0] === "MYAPP") {
parts = parts.slice(1);
}
for (i = 0; i < parts.length; i += 1) {
// create a property if it doesn‘t exist
if (typeof parent[parts[i]] === "undefined") {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
// assign returned value to a local var var module2 = MYAPP.namespace(‘MYAPP.modules.module2‘); module2 === MYAPP.modules.module2; // true // skip initial `MYAPP` MYAPP.namespace(‘modules.module51‘); // long namespace MYAPP.namespace(‘once.upon.a.time.there.was.this.long.nested.property‘);

JavaScript基础对象创建模式之命名空间(Namespace)模式(022)
标签:style blog http io 使用 java ar strong for
原文地址:http://www.cnblogs.com/Bryran/p/3976134.html