WindowsMaker
WindowsMaker

Reputation: 3400

javascript namespace definition self reference

I am trying to define a javascript namespace, but within the namespace i have objects that are extensions of basic classes (using backbone and underscore):

namespace = {
    subspace: {
        A: some_class.extend({...}),
        B: A.extend({...})
    }
}

but this creates a problem because A is not yet defined. What is the best practice in this situation? furthermore, i have multiple subspaces in this namespace and subsequent ones cannot reference the previous one.

namespace = {
    subspace: {
        A: some_class.extend({...}),
        B: A.extend({...})
    },
    subspace2: {
        some_function: function(){
            <how do i create an instance of A for example? > 
        }
    }
}

Upvotes: 0

Views: 146

Answers (1)

Evgeniy
Evgeniy

Reputation: 2921

You should use helper function to manage it. Here is an implementation from "JavaScript Patterns" by Stoyan Stefanov.

Consider application global object as MYAPP.

and function of adding namespaces:

MYAPP.namespace('MYAPP.modules.module1')

and here is example implementation of namespace method:

MYAPP.namespace = function(ns_string) {
    var parts = ns_string.split('.'),
        parent = MYAPP,
        i;

    if (parts[0] === 'MYAPP') {
        parts = parts.slice(1);
    }

    for (i=0; i<parts.length; i++) {
        if(typeof parent[parts[i]] === 'undefined') {
            parent[parts[i]] = {}
        }
        parent = parent[parts[i]];
    }

    return parent;
}

Upvotes: 1

Related Questions