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

转载于:https://www.cnblogs.com/davidgu/p/3333129.html

猜你喜欢

转载自blog.csdn.net/weixin_33720956/article/details/93802898