首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 5.1 Namespace Pattern

2024-04-27 14:22:23
字体:
来源:转载
供稿:网友

javaScript Patterns 5.1 Namespace Pattern

2014-06-22 23:16 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

global namespace object

// global objectvar MYAPP = {};// constructorsMYAPP.Parent = function() {};MYAPP.Child = function() {};// a variableMYAPP.some_var = 1;// an object containerMYAPP.modules = {};// nested objectsMYAPP.modules.module1 = {};MYAPP.modules.module1.data = {    a : 1,    b : 2};MYAPP.modules.module2 = {};

Drawbacks

• A bit more to type; PRefixing every variable and function does add up in the total amount of code that needs to be downloaded

• Only one global instance means that any part of the code can modify the global instance and the rest of the functionality gets the updated state

• Long nested names mean longer (slower) property resolution lookups

General Purpose Namespace Function

// unsafevar MYAPP = {};// betterif ( typeof MYAPP === "undefined") {    var MYAPP = {};}// or shortervar MYAPP = MYAPP || {};// using a namespace functionMYAPP.namespace('MYAPP.modules.module2');// equivalent to:// var MYAPP = {//      modules: {//              module2: {}//      }// };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 varvar module2 = MYAPP.namespace('MYAPP.modules.module2');module2 === MYAPP.modules.module2;// true// skip initial `MYAPP`MYAPP.namespace('modules.module51');// long namespaceMYAPP.namespace('once.upon.a.time.there.was.this.long.nested.property');

References:

Javascript Patterns - by Stoyan Stefanov(O`Reilly)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表