global namespace object

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

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

// 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: {}

//      }

// };

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');

 References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 5.1 Namespace Pattern的更多相关文章

  1. JavaScript Patterns 5.5 Sandbox Pattern

    Drawbacks of the namespacing pattern • Reliance on a single global variable to be the application’s ...

  2. JavaScript Patterns 5.4 Module Pattern

    MYAPP.namespace('MYAPP.utilities.array'); MYAPP.utilities.array = (function () { // dependencies var ...

  3. JavaScript Patterns 5.8 Chaining Pattern

    Chaining Pattern - Call methods on an object one after the other without assigning the return values ...

  4. JavaScript Patterns 4.2 Callback Pattern

    function writeCode(callback) { // do something... callback(); // ... } function introduceBugs() { // ...

  5. JavaScript Patterns 2.6 switch Pattern

    Principle • Aligning each case with switch(an exception to the curly braces indentation rule). • Ind ...

  6. JavaScript Patterns 4.8 Function Properties - A Memoization Pattern

    Gets a length property containing the number of arguments the function expects: function func(a, b, ...

  7. JavaScript Patterns 7.1 Singleton

    7.1 Singleton The idea of the singleton pattern is to have only one instance of a specific class. Th ...

  8. JavaScript Patterns 6.7 Borrowing Methods

    Scenario You want to use just the methods you like, without inheriting all the other methods that yo ...

  9. JavaScript Patterns 6.5 Inheritance by Copying Properties

    Shallow copy pattern function extend(parent, child) { var i; child = child || {}; for (i in parent) ...

随机推荐

  1. 第 18 章 CSS 表格与列表

    学习要点: 1.表格样式 2.列表样式 3.其他功能 主讲教师:李炎恢 本章主要探讨 HTML5 中 CSS 表格和列表,通过表格和列表的样式设置,让表格和列表显示更加多元化. 一.表格样式 表格有五 ...

  2. Web-Nginx配置

    #运行用户 user nobody; #启动进程,通常设置成和cpu的数量相等 worker_processes 1; #全局错误日志及PID文件 #error_log logs/error.log; ...

  3. bootstrap框架禁用谷歌字体

    bootstrap框架禁用谷歌字体 H5框架换字体.png

  4. ahjesus 前端缓存原理 转载

    LAMP缓存图 从图中我们可以看到网站缓存主要分为五部分 服务器缓存:主要是基于web反向代理的静态服务器nginx和squid,还有apache2的mod_proxy和mod_cache模 浏览器缓 ...

  5. mysql定时任务简单例子

    mysql定时任务简单例子 ? 1 2 3 4 5 6 7 8 9     如果要每30秒执行以下语句:   [sql] update userinfo set endtime = now() WHE ...

  6. C#之第五单元的项目打印购物单

    人生的坚持,学习的坚持,尽管遭遇困苦,但是我们却能在一次次的苦难中成长,重新爬起来.这就是奋斗的人生.就是挥洒自己青春,汗水的有意义,有价值的生活.而,我虽然在平凡的人群中不起眼,可是每个人却闪耀着自 ...

  7. mysql hang and srv_error_monitor_thread using 100% cpu

    昨天晚上,运维过来说有台生产服务器的mysql cpu一直100%,新的客户端登录不了,但是已经在运行的应用都正常可用. 登录服务器后,top -H看了下,其中一个线程的cpu 一直100%,其他的几 ...

  8. Lisp学习--Windows下面的开发环境搭建

    很久以前,就准备学习Lisp,但是遇到不少困难,社区太凌乱,也一直很犹豫,直到看了<Common Lisp - 想说爱你不容易>,想看看Common Lisp怎么样,之前都是拿Lisp的方 ...

  9. Quartz任务调度器

    在使用jdk的timer时发现无法满足开发需求:即无法在指定的日期进行执行任务. 这便引入一个优秀的开源任务调度框架“quartz”.   这里加入的是quartz-1.8.6版本.Quart的官网: ...

  10. Quartz.NET开源作业调度框架系列(五):AdoJobStore保存job到数据库

    Quartz.NET 任务调度的核心元素是 scheduler, trigger 和 job,其中 trigger(用于定义调度时间的元素,即按照什么时间规则去执行任务) 和 job 是任务调度的元数 ...