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. QTableWidget详解(样式、右键菜单、表头塌陷、多选等) 2013-10-23 10:54:04

    一.设置表单样式 点击(此处)折叠或打开 table_widget->setColumnCount(4); //设置列数 table_widget->horizontalHeader()- ...

  2. jdk源码分析之ArrayList

    ArrayList关键属性分析 ArrayList采用Object数组来存储数据 /** * The array buffer into which the elements of the Array ...

  3. Java的HashSet类

    如果要查找一个集合中是否包含了某个对象,那么就需要把这个对象和这个集合中的每个对象依次进行比较和判断,直到找到这个对象为止,或者把所有对象都比较一次为止(如果最后一个对象才是要查找的对象,或者集合中没 ...

  4. 【Java每日一题】20161122

    package Nov2016; import java.util.ArrayList; import java.util.Iterator; public class Ques1122 { publ ...

  5. PostgreSQL获取年月日

    1.获取当前日期的年份 select to_char(t.detect_date,'YYYY') select extract(year from now())为double precision 格式 ...

  6. 泛函编程(38)-泛函Stream IO:IO Process in action

    在前面的几节讨论里我们终于得出了一个概括又通用的IO Process类型Process[F[_],O].这个类型同时可以代表数据源(Source)和数据终端(Sink).在这节讨论里我们将针对Proc ...

  7. Thinkphp各种方法知识图谱

    A方法:用于实例化控制器 ThinkPHP函数详解:A方法 B方法:执行某个行为 I方法(其命名来自于英文Input):获取输入参数 支持过滤和默认值 ThinkPHP函数详解:I方法 D方法:D函数 ...

  8. 如何订阅Form的自定义事件

    Window Form类有很多的属性/方法和事件,其中事件属于一种发布订阅模式 .订阅发布模式定义了一种一对多的依赖关系,让多个订阅者对象同时监听某一个主体对象.这个主体对象在自身状态变化时,会通知所 ...

  9. Numeral.js – 格式化和操作数字的 JavaScript 库

    Numeral.js 是一个用于格式化和操作数字的 JavaScript 库.数字可以格式化为货币,百分比,时间,甚至是小数,千位,和缩写格式,功能十分强大.支持包括中文在内的17种语言. 您可能感兴 ...

  10. PNotify – 简单易用的 JS 通知,消息提示插件

    PNotify 是一个 JavaScript 通知插件,前身为 Pines Notify.它旨在提供无与伦比的灵活性,同时很容易使用.它可以提供无阻塞的通知,允许用户无需关闭通知或者提示信息就可以点击 ...