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. PDF解析帮助类

    public class ComPDFHepler { /// <summary> /// 正则获取字符串中两个字符串间的内容 /// </summary> /// <p ...

  2. 反编译APK文件

    有时源代码丢失了,这时如果有apk文件的话,是可以对apk文件反编译得到源文件的,本文介绍一下简单的反编译apk文件的过程. 1.工具 反编译apk需要的工具有两个:apk2java和apktool, ...

  3. 删除Android包

    Android删除包有很多种方法,其中一种通过Intent删除,代码如下: public boolean unload (String n){ boolean res = true; try{ // ...

  4. ListActivity的使用

    Android中经常用到列表,ListActivity是实现列表的一种好方法. 使用ListActivity的方法,首先定义布局文件: <?xml version="1.0" ...

  5. 修正 XE6 TListView 上方 SearchBok 右边的清除钮显示

    注意:XE7 已修正这个问题. Delphi Firemonkey TListView 提供了搜寻的功能,但在 XE6 以前的版本,可以显示右边的清除按钮,在 XE6 确消失了,这里提供一个修正的方案 ...

  6. ios源码-ios游戏源码-ios源码下载

    游戏源码   一款休闲类的音乐小游戏源码 该源码实现了一款休闲类的音乐小游戏源码,该游戏的源码很简单,而且游戏的玩法也很容易学会,只要我们点击视图中的grid,就可以 人气:2943运行环境:/Xco ...

  7. java.lang.IllegalStateException: Failed to read Class-Path attribute from manifest of jar file:/XXX

    出现这个问题的解决方案就是将原有的jar删除  然后重新下载过一遍就可以使用了  我估计是元数据等损坏了

  8. 第 14 章 CSS 颜色与度量单位

    学习要点: 1.颜色表方案 2.度量单位 主讲教师:李炎恢 本章主要探讨 HTML5 中 CSS 颜色和度量单位等问题,包括颜色的选取方式.相对长度和绝对长度等. 一.颜色表方案 颜色的表现形式主要有 ...

  9. Servlet与多线程与IO操作

    1.JVM内存模型相关概念 2.Java多线程并发深入理解 3.Servlet.设计模式.SpringMVC深入理解 4.Java基础遗漏点补充 数据库连接池:JDBC connection pool ...

  10. Ext.Net MVC 配置(1)

    1.在VS2012中创建MVC3项目 2.在项目总启动NuGet,在里面安装Ext.net 3.安装Ext.net 4.安装完成后项目中相关的配置文件就会有所改变了. 5.测试:运行mvc项目:htt ...