1

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();
2
  • Ok, but do I have to write 100 times NS.A for every property or function I want to access? Or should I better create a local variable pointing to NS.A? As a matter of fact, I am trying the second, but don't find it clean either. Commented Apr 17, 2011 at 16:54
  • You should read about javascript closure. Having a local variable within scoop pointing outside to NS.A will definitely be faster than referring a variable outside the scoop. Commented Apr 17, 2011 at 17:03

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.