user287966
user287966

Reputation: 33

JavaScript namespaces

Which is the best way to access a function or property from one namespace within another in JavaScript? Example:


var NS = {};  
NS.A = {  
    prop1: 'hello',
    prop2: 'there',
    func: function() {alert('boo');}  
};  

NS.B.C = {  

    func1: function() {
        // Here I want to access the properties and function from the namespace above
        alert( NS.A.prop1 + NS.A.prop2 ); // ?
        NS.A.func(); // ?
    }

};

NS.B.C.func1();

Upvotes: 1

Views: 380

Answers (2)

Mickel
Mickel

Reputation: 6696

NS.B.C causes the error... something like this should work for you:

NS.B = {
  C: {
    func1: function() {
        // Here I want to access the properties and function from the namespace above
        alert( NS.A.prop1 + NS.A.prop2 ); // ?
        NS.A.func(); // ?
    }
  }
};

See http://jsbin.com/eweta5/2 for example.

Upvotes: 2

Quentin
Quentin

Reputation: 943556

Of course, a "namespace" in JavaScript is just a global object where a collection of associated functions and pieces of data are stored (instead of having lots of globals, one for each function and piece of data).

The only reason your example won't work is that NS.B is undefined when you try to assign a C property to it.

Upvotes: 4

Related Questions