I started using the module template in my project. As I understand it, it looks something like this:
var obj = (function(foo){
It looked pretty good on paper and, in practice, seems to work quite well. The initialization logic above is intuitive, then private methods, and then publicly available.
I ran into one problem. How can I call publicFoo or publicBar outside the scope of the return statement and inside the scope of the obj function declaration?
My current solution is to do something like:
var obj = (function(foo){ //Private methods declared early for use. var privateBazz = function(){ return "I'm known only to this closure!"; }(); var privateBar = function(){ return foo + privateBazz; }; //Some initialization logic up here. var dependentOnBar = privateBar(); //Public methods return { publicFoo: foo, publicBar: privateBar } })();
This works, but all of a sudden my personal variable declarations are placed over the private property declarations of the objects. The problem will be compounded if I try to keep the declarations of the private function as close as possible to the code that first calls them, so I just declared all the private functions that I need at the top, and then initialized the properties afterwards. Again, this works, but I'm used to having the code as close to the execution point as possible. So, declaring private function blocks at the top is really inconvenient for me. Does anyone else feel like this, or is it just that I just need to get into JavaScript? Are there any steps that I should take when I see this?
source share