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:
- I understand that
XULSchoolChromeis an object with a property namedBrowserOverlay. But then what arefirst_nameandonmenuclick? Are they sub-properties ofBrowserOverlayobject? - If I need to access
first_nameinsideonmenucickfunction, it has to be fully qualifiedXULSchoolChrome.BrowserOverlay.first_name. This can quickly get unwieldy for non-trivial code. Is there a more graceful way of simulating namespaces in Javascript?
Thanks.
Yes, they are properties of the object which is references by the
BrowserOverlayproperty of theXULSchoolChromeobject.No, you always need to reference properties via the object. However, you can abbreviate sub-namespaces to variables:
Or you might be able to use the
thiskeyword from “methods” of the namespace object. Notice that this won’t work directly for event handler functions, which are usually called in different contexts.