Can I combine the declaration of the function with the assignment operator? I'm aware of immediately invoked function expressions but I wasn't sure off-hand if this approach would behave like calling the new operator.
It'd save quite a few lines of code if it could be combined. The function is always instantiated only once and assigned to a namespace variable, so there's no need to have them as separate statements if it's not needed.
function internalLoginMobileModule () {
var self = this;
self.initializeForm = function () {
//
};
return self;
};
app.form.mobile.internalLogin = new internalLoginMobileModule();
Edit:
Object initializers are very clean, but too limited in my case. I need the power that the lexical scope provides. These "modules" that are stored in the global namespace contain operations that demand "private" functions, and code re-use within the module (i.e. being able to access methods within that object using this/self
. Here's an example of a module that I have demonstrating the use (notice the use of self
, as well as the private function _setDefaultButtonForArea):
var UIHelperModule = function () {
var self = this;
self.getExtJsElementByName = function (name) {
// Find Ext JS by name
};
self.isExtJsElementEnabled = function (name) {
return !self.getExtJsElementByName(name).disabled;
};
function _setDefaultButtonForArea (areaName, areaId, buttonName) {
// Set Default Button
}
self.setDefaultButton = function (buttonName) {
_setDefaultButtonForArea(null, window.thisForm.id, buttonName);
};
self.setDefaultButtonForAreaName = function (areaName, buttonName) {
_setDefaultButtonForArea(areaName, null, buttonName);
};
self.setDefaultButtonForAreaId = function (areaId, buttonName) {
_setDefaultButtonForArea(null, areaId, buttonName);
};
self.triggerClickForElementName = function (buttonName) {
var foundExtJsElement = self.getExtJsElementByName(buttonName);
// Make sure the button exists
if (foundExtJsElement) {
foundExtJsElement.el.dom.click()
}
};
return self;
}
app.ui = new UIHelperModule();