I have a question about best practices with the Module Design Pattern. The code below is an example of the way that some of our Components are written (we use ExtJs but tha
First, this isn't specifically a module design pattern as I know it, this is a general constructor pattern. The module pattern I know is a singleton, but here you could have many instances of Foo(). That being said...
Q: How important is it to initialize variables when they're declared (i.e. at the top of Foo)
Declaring them at the top is important for clarity, but initializing them isn't as important here since you're doing so in the init. If you weren't doing this, initializing them prevents you from having to do an undefined check before testing the variable later:
var x;
function baz(){
if (typeof(x) === 'undefined') {
// init
} else {
if (x > 0) { blah } else { blah blah }
}
}
Q: How might I re-initialize part of this object if a client of this Module gets to a state that it's foo object needs to be set back to it's originals
Is there something wrong with creating a public reset method? It will have access to the private variables.
function Foo() {
// ...
this.reset = function () {
privateNumber = 0;
// etc
};
// ...
}
Q: What sort of memory issues might this design lead to and how can I refactor to mitigate that risk?
I don't know.
Q: Where can I learn more? Are there any articles that address this without relying too much on the latest and greatest of EcmaScript 5 ?
Here's a good read about the Javascript module (and other) pattern(s): http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript