Js Pattern - Namespace Pattern

bad code

// 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 = {};

 

good code

// 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 = {};

 

Some of the properties you’re adding to the namespace may already exist, and you could be overwriting them.
Therefore before adding a property or creating a namespace, it’s best to check first that it doesn’t already exist

// unsafe
var MYAPP = {};

// better
if (typeof MYAPP === "undefined") {
    var MYAPP = {};
}

// or shorter
var MYAPP = MYAPP || {};

 

 

posted @ 2013-09-22 15:07  Master HaKu  阅读(510)  评论(0编辑  收藏  举报