zoukankan      html  css  js  c++  java
  • JavaScript Patterns 5.1 Namespace Pattern

    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)

  • 相关阅读:
    vsftp 虚拟用户测试
    RHEL7 MariaDB测试
    安装xenapp后,非管理员连接RDP出现桌面当前不可用的解决方法
    sqrt函数的实现
    O2O、C2C、B2B、B2C
    libsvm使用说明
    如何确定最适合数据集的机器学习算法
    知乎日报:她把全世界的学术期刊都黑了
    逻辑回归应用之Kaggle泰坦尼克之灾
    非均衡数据分布的分类问题
  • 原文地址:https://www.cnblogs.com/haokaibo/p/Namespace-Pattern.html
Copyright © 2011-2022 走看看