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. DevExpress winform XtraEditor常用控件

    最近在公司里面开始使用DevExpress winform的第三方控件进行开发和维护,这里整理一些常用控件的资料以便于后续查看 ComboBoxEdit 这个控件和winform自带的控件差不多,使用 ...

  2. Firemonkey 载入 Style 皮肤 (*.fsf 二进制文件) 速度测试

    说明:Firemonkey 可以换肤是一大亮点,但使用它必须要付出一点代价,就是需要一点载入的时间,下面以 *.fsf 二进制文件来做载入测试,有兴趣可以参考看看. 开发:XE8 for iOS 皮肤 ...

  3. Delphi 收藏

    日前整理仓库,翻出了一些 Delphi 产品,以前购买的 Delphi 都有实体产品,包含说明书.光碟片.还有一些广告文宣,而且相当厚实,版本的演进,从外包装也能感受到,到目前的 XE5 版,只剩一个 ...

  4. Java--简单的Spring AOP配置以及AOP事物管理,JDK/GCLib动态代理

    一.看一下简单的通过XML的AOP配置 1.首先创建一个简单的Student类 public class Student { private Integer age; private String n ...

  5. 计划任务crontab

    安装crontab服务 1, yum install -y vixie-cron 如果提示crond命令不存在,可能被误删除了,CentOS下可以通过这个命令重新安装: yum -y install ...

  6. PHP 批量生成静态文件目录代码

    <?php /** * @author:jiangzaixing 20160314 * 获取静态文件方法 */ class StaticFile { const MAP_FILE_NAME = ...

  7. CSDN数据库被爆 统计CSDN用户都喜欢哪些密码

    今天有黑客在网上公开了知名网站CSDN的用户数据库,这是一次严重的暴库泄密事件,涉及到的账户总量高达600万个.有人写了一个小程序,统计了这次公布的 6428632 个 CSDN 哪些密码出镜率较高? ...

  8. store.js - 轻松实现本地存储(LocalStorage)

    store.js 是一个兼容所有浏览器的 LocalStorage 包装器,不需要借助 Cookie 或者 Flash.store.js 会根据浏览器自动选择使用 localStorage.globa ...

  9. Horseman - 让你更轻松的使用 PhantomJS

    Horseman 是一个 Node.js 模块,让你可以更轻松的使用 PhantomJS 进行功能测试,页面自动机,网络监控,屏幕捕获等.它提供了直接,链式的 API,易于理解的控制流,避免回调陷阱. ...

  10. .net c# 视频剪切抓取缩略图

    public string Cut(string ffmpegPath, string videoPath, string savePath, string imgSize, int sleepTim ...