JavaScript first-class function limitation
Yesterday I needed to use a specific Object Oriented pattern to program a JavaScript module. My module was kind of a big object that contains other objects (sub-module).
The object literal notation
subModule1: {
method1: function () { },
method2: function () { }
},
subModule2: {
method1: function () { },
method2: function () { }
}
};
Because I needed to use closures for the module and it’s sub-modules, so I can keep the state of my system within the proper module, I didn’t want to use the object literal notation to code my module.
Instead I used functions to return my module properties, so I can declare variables just above the return statement of the module, so every properties can access them EVEN WHEN the function will return, e.g. until the program is loaded in memory.
The real way I did it
var foo;
return {
subModule1: function () {
var bar;
return {
method1: function () { },
method2: function () { }
};
}(),
subModule2: function () {
var bar;
return {
method1: function () { },
method2: function () { }
};
}()
};
}();
I realized that it was not possible to refer to the properties of the precedent subModules within a subModule closure section (above the return statement), since the subModules are not an object literal, but a function that return an object.
I was astonished that I cannot access the bigModule properties, but deeper from within another function:
// purpose of this article
// to make sure it has never
// already returned the object.
var bigModule = function () {
var foo;
return {
subModule1: function () {
var bar;
return {
method1: function () {
alert("subModule1.method1() called");
},
method2: function () { }
};
}(),
subModule2: function () {
// Error: bigModule has no properties //
bigModule.subModule1.method1();
return {
method1: function () {
// OK!, bigModule has already returned here //
bigModule.subModule1.method1();
},
method2: function () { }
};
}()
};
}();
Even if I can do some hacks (some ugly, some ok, depending of what I want to achieve) to make it possible to access the bigModule variable once returned, before the return statement of the subModule2 property, I’m still confused and wonder if that pattern of programmation is really powerful or is limited (e.g. nested function literals).
I’m going to study it and understand that behavior. It seems that a function literal won’t be executed until it stops stacking deeper function literals.
Any explications?