I am somewhat new to Javascript (been using it for a few months), but overall I would probably consider myself a borderline novice/intermediate programmer. I am now working on a fairly large project in Javascript, containing many different functions, and I am trying to figure out some "best practices" for organizing my code.
I have seen a few examples of an approach that seems potentially very helpful. For example, see this Stackoverflow answer, or this page on best practices (do a Ctrl+F for return{). Essentially, you define a function in a variable, and that function simply returns other functions/variables:
var functionContainer = function() {
return {
function1 : function () {
// Do something
},
function2 : function () {
// Do something else
}
};
}();
This seems helpful in cases where I have multiple functions that do similar things; I can put them all into a "container" of sorts, and then call them with functionContainer.function1();.
Essentially, my question is: Is there a name for this technique? Can you recommend any sources for further reading? A lot of sources that I've seen don't go into great depth about what exactly is going on when you do this, and I want to be sure that I fully understand what I'm doing before I start shuffling around a bunch of my code.
I may post some separate follow-up questions later, depending on the responses I get here. If so, I will post links to them here, for anyone else who's curious.
Revealing Module Pattern http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript
Addy Osmani's Analysis copied from link above:
Advantages
This pattern allows the syntax of our scripts to be more consistent. It also makes it more clear at the end of the module which of our functions and variables may be accessed publicly which eases readability.
Disadvantages
A disadvantage of this pattern is that if a private function refers to a public function, that public function can't be overridden if a patch is necessary. This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions.
Public object members which refer to private variables are also subject to the no-patch rule notes above.
As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With