require

require module

by davidhong

JavaScript

var GLOBAL = this;

/**
 * load given namespace if it exists
 *
 * @static
 * @param {object} context scope, if null or undefined - global object will be used
 * @param {string} namespace to load
 * @param {function} callback function. object at given namespace is passed as argument [optional]
 * @returns object at given namespace
 */
var require = function(context, namespace, callback) {
    "use strict";

    if (typeof namespace !== 'string') {
        return;
    }

    var current = context || GLOBAL,
        ns_tree = String.prototype.split.call(namespace, '.'),
        ns_depth = ns_tree.length,
        ns_index = 0;

    for (ns_index; ns_index < ns_depth; ns_index++) {
        var ns_next = ns_tree[ns_index];

        if (!current[ns_next]) {
            return;
        }

        current = current[ns_next];
    }

    if (typeof callback === 'function') {
        callback.call(context, current);
    }

    return current;
};

// DOMWindow
require(null, 'window', function(w) {
    console.log(w);
});

// split() function
require('hello', 'split', function(s) {
    console.log(s);
});

// call() function
require(parseInt, 'call', function(pi) {
    console.log(pi);
});

//
(function(require) {
    var o = {
        a: {
            z: 1,
            y: 1,
            x: 1,
            w: 1,
            u: 1,
            v: 1,
            s: 1,
            t: 1,
            r: 1,
            p: 1,
            q: 1,
            o: 1,
            m: 1,
            n: 1,
            b: {
                z: 1,
                y: 1,
                x: 1,
                w: 1,
                u: 1,
                v: 1,
                s: 1,
                t: 1,
                r: 1,
                p: 1,
                q: 1,
                o: 1,
                m: 1,
                n: 1,
                c: {
                    z: 1,
                    y: 1,
                    x: 1,
                    w: 1,
                    u: 1,
                   ...