Sandbox pattern

messing with the sandbox pattern

by Eric Hynds

JavaScript

// messing with the sandbox pattern

function AP(){
    var args = Array.prototype.slice.call(arguments),
        callback = args.pop(),
        modules = (args[0] && typeof args[0] === "string") ? args : args[0],
        i;
    
    // make sure we call this as a constructor
    if(!(this instanceof AP)){
        return new AP(modules,callback);
    }
    
    // add modules to "this"
    modules = [];
    for(i in AP.modules){
        if(AP.modules.hasOwnProperty(i) && typeof AP.modules[i] === "function"){
            modules.push(i);
        }
    }
    
    // init modules
    for(i=0, len = modules.length; i < len; i++){
        AP.modules[modules[i]](this);
    }
    
    // fire callback
    callback(this);
}

AP.prototype = {
    version: 1
};

// add some modules
AP.modules = {
    vessels: function(){},
    
    members: function( instance ){
        
        // "this" is the AP.modules object
        // "instance" is the AP.prototype + defined members
        console.log("members", this, instance);
    }
};


// with this, "members" object will run in full
AP('members', function(instance){
    // "this" is the window
    // "instance" is AP instance
    console.log("inside callback", this, instance);
});