Drawbacks of the namespacing pattern

• Reliance on a single global variable to be the application’s global. In the namespacing pattern, there is no way to have two versions of the same application or library run on the same page, because they both need the same global symbol name, for example, MYAPP.

• Long,  dotted  names  to  type  and  resolve  at  runtime,  for  example, MYAPP.utilities.array.

A Global Constructor

Using the sandbox will look like this:

new Sandbox(function (box) {

    // your code here...

});

The  object  box will  be  like  MYAPP in  the  namespacing  example—it  will  have  all  the library functionality you need to make your code work.

Sandbox(['ajax', 'event'], function (box) {

    // console.log(box);

}); 

module names are passed as individual argument

Sandbox('ajax', 'dom', function (box) {

    // console.log(box);

}); 

when no modules are passed, the sandbox will assume '*'.

Sandbox('*', function (box) {

    // console.log(box);

});

Sandbox(function (box) {

    // console.log(box);

}); 

protect the global namespace by having your code wrapped into callback functions.

Sandbox('dom', 'event', function (box) {

    // work with dom and event

    Sandbox('ajax', function (box) {

        // another sandboxed "box" object

        // this "box" is not the same as

        // the "box" outside this function

        //...

        // done with Ajax

    });

    // no trace of Ajax module here

}); 

Adding Modules

Sandbox.modules = {};

Sandbox.modules.dom = function (box) {

    box.getElement = function () {};

    box.getStyle = function () {};

    box.foo = "bar";

};

Sandbox.modules.event = function (box) {

    // access to the Sandbox prototype if needed:

    // box.constructor.prototype.m = "mmm";

    box.attachEvent = function () {};

    box.dettachEvent = function () {};

};

Sandbox.modules.ajax = function (box) {

    box.makeRequest = function () {};

    box.getResponse = function () {};

};

Implementing the Constructor

function Sandbox() {

    // turning arguments into an array

    var args = Array.prototype.slice.call(arguments),

        // the last argument is the callback

        callback = args.pop(),

        // modules can be passed as an array or as individual parameters

        modules = (args[0] && typeof args[0] === "string") ? args : args[0],

        i;

    // make sure the function is called

    // as a constructor

    if (!(this instanceof Sandbox)) {

        return new Sandbox(modules, callback);

    }

    // add properties to `this` as needed:

    this.a = 1;

    this.b = 2;

    // now add modules to the core `this` object

    // no modules or "*" both mean "use all modules"

    if (!modules || modules === '*') {

        modules = [];

        for (i in Sandbox.modules) {

            if (Sandbox.modules.hasOwnProperty(i)) {

                modules.push(i);

                // Sandbox.modules[i](this);

            }

        }

    }

    // initialize the required modules (Kaibo: The code below in yellowcan be omitted by the code in yellow above to avoid the 2nd loop)

    for (i = 0; i < modules.length; i += 1) {

        Sandbox.modules[modules[i]](this);

    }

    // call the callback

    callback(this);

}

// any prototype properties as needed

Sandbox.prototype = {

    name: "My Application",

    version: "1.0",

    getName: function () {

        return this.name;

    }

};

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)

JavaScript Patterns 5.5 Sandbox Pattern的更多相关文章

  1. JavaScript Patterns 5.8 Chaining Pattern

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

  2. JavaScript Patterns 5.4 Module Pattern

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

  3. JavaScript Patterns 5.1 Namespace Pattern

    global namespace object // global object var MYAPP = {}; // constructors MYAPP.Parent = function() { ...

  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. Git tag 给当前分支打标签

    原文已经找不到出处,重新整理格式,仅作个人收藏! 标签(Tag)可以针对某一时间点的版本做标记,常用于版本发布. 列出tag $ git tag # 在控制台打印出当前仓库的所有tag $ git t ...

  2. mysql对表操作的各种语句

    创建表 create table tb_user( id int(类型)primary key(设置为主键) auto_increment (设置id自增长), 每一个字段用逗号隔开, name va ...

  3. Gym 100917J---dir -C(RMQ--ST)

    题目链接 http://codeforces.com/gym/100917/problem/D problem description Famous Berland coder and IT mana ...

  4. Scalaz(39)- Free :a real monadic program

    一直感觉FP比较虚,可能太多学术性的东西,不知道如何把这些由数学理论在背后支持的一套全新数据类型和数据结构在现实开发中加以使用.直到Free Monad,才真正感觉能用FP方式进行编程了.在前面我们已 ...

  5. (学习笔记)HTML的<link>标签

    在HTML中<link>标签用于定义文档与外部资源的关系. <link>标签只存在于head部分. <head> <link rel="styles ...

  6. CentOS 6.5下Redis安装详细步骤

    Redis简介: Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis的开发工 ...

  7. 修改windows系统文件权限

    修改windows系统文件总是提示没有权限,虽然已是administrator也不管用. 以下方法可以解决: 右键属性,安全,高级,所有者,编辑,选择当前用户并确定, 回到上一页再确定, 然后在安全页 ...

  8. GJM : FlatBuffers 与 protobuf 性能比较 [转载 ]

    原帖地址:http://blog.csdn.net/menggucaoyuan/article/details/34409433 原作者:企鹅  menggucaoyuan 未经原作者同意不允许转载 ...

  9. 七个结构模式之享元模式(Flyweight Pattern)

    定义: 运用共享技术对大量细粒度对象的复用,这要求这些对象都很相似,状态变化很小.将这些对象的内部状态和外部状态进行区分,对于内部状态相同的只存储一个对象,而对不同的外部状态则采用不同的操作. 结构图 ...

  10. Resumable.js – 基于 HTML5 File API 的文件上传

    Resumable.js 是一个 JavaScript 库,通过 HTML5 文件 API 提供,稳定和可恢复的批量上传功能.在上传大文件的时候通过每个文件分割成小块,每块在上传失败的时候,上传会不断 ...