Reputation: 173
I have started learning Javascript as part of developing very simple Firefox addons. The Firefox addon tutorial advises to encapsulate all the functions and data inside a namespace like this.
if ("undefined" == typeof(XULSchoolChrome)) {
var XULSchoolChrome = {};
};
XULSchoolChrome.BrowserOverlay = {
first_name : new String,
onmenuclick : function(aEvent) {
// do something here
}
};
I have a couple of questions related to this:
XULSchoolChrome
is an object with a property named BrowserOverlay
. But then what are first_name
and onmenuclick
? Are they sub-properties of BrowserOverlay
object?first_name
inside onmenucick
function, it has to be fully qualified XULSchoolChrome.BrowserOverlay.first_name
. This can quickly get unwieldy for non-trivial code. Is there a more graceful way of simulating namespaces in Javascript?Upvotes: 1
Views: 116
Reputation: 664620
But then what are first_name and onmenuclick?
Yes, they are properties of the object which is references by the BrowserOverlay
property of the XULSchoolChrome
object.
Is there a more graceful way of simulating namespaces in Javascript?
No, you always need to reference properties via the object. However, you can abbreviate sub-namespaces to variables:
var bo = XULSchoolChrome.BrowserOverlay;
// then use
bo.first_name…
bo.…
Or you might be able to use the this
keyword from "methods" of the namespace object. Notice that this won't work directly for event handler functions, which are usually called in different contexts.
Upvotes: 1