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. 2013ACM/ICPC亚洲区南京站现场赛---Poor Warehouse Keeper(贪心)

    题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=4803 Problem Description Jenny is a warehouse keeper. ...

  2. [moka同学笔记]Yii下国家省市三级联动

    第一次做省市三级联动时候遇到了坑,感觉还是自己太菜.头疼了很久研究了很久,最后终于发现了问题.大致总结一下思路 在控制器中实例化model,然后在视图中渲染所有国家,当选取国家时候,ajax通过 id ...

  3. HDU 1131 Count the Trees 大数计算

    题目是说给出一个数字,然后以1到这个数为序号当做二叉树的结点,问总共有几种组成二叉树的方式.这个题就是用卡特兰数算出个数,然后因为有编号,不同的编号对应不同的方式,所以结果是卡特兰数乘这个数的阶乘种方 ...

  4. Python中类的定义

    class Student(object): # 有点类似其它高级语言的构造函数 def __init__(self,name,score): self.name = name self.score ...

  5. linux TCP: time wait bucket table overflow

    早上一台rabbitmq和Java所在的服务器,客户端反馈超级卡,看io和cpu都不高.发现六七万消息挤压,临时性问题解决之后,看/var/log/messages,发现很多TCP: time wai ...

  6. Spring4学习笔记2-配置Bean

    1.配置bean 配置形式:Xml和注解方式 Bean的配置方式:通过全类名(反射).工厂.FactoryBean 1.1 id必须唯一 2 Spring提供两种类型的IOC容器的实现 BeanFac ...

  7. 决战大数据之二:CentOS 7 最新JDK 8安装

    决战大数据之二:CentOS 7 最新JDK 8安装 [TOC] 修改hostname # hostnamectl set-hostname node1 --static # reboot now 重 ...

  8. Exchange 2013 、Lync 2013、SharePoint 2013 三

    前两篇介绍的是关于Exchange 与 Lync 之间的配制关系,这一篇介绍关于Lync.Exchange 与 SharePoint 之间建立信任关系. 首先要创建基于SSL的SharePoint A ...

  9. WPF钟表效果实现

    WPF在样式定义和UI动画上面相对于以前的技术有了不少的提升,下面给出WPF技术实现钟表的效果: 1.Visual Studio新建一个WPF应用程序,命名为WpfClock,新建一个images文件 ...

  10. 在你设计中可能用到的20个杂志 PSD 原型

    你是否正在为您的印刷产品找一些现成的原型素材?在这里,我们收集了一组免费的杂志 PSD 素材,必将派上用场.这些原型将给你和你的客户一个先睹为快的产品,在现实生活中看起来如何.所有这些原型提供了可以免 ...