I’ve read a lot of things about the module pattern.
Ok It brings structure, private method, etc…
But with the code below I can get the same behavior without using it.
function Human()
{
// private properties
var _name='';
var _age=0;
// private methods
function created()
{
console.log("Human "+_name+" called");
};
// public
this.setName = function(name){
_name=name;
created();
};
}
var h1 = new Human();
h1.setName("John");
So, what are the real advantage of a module pattern finally ?
I think this example could help you to clarify the usefulness of the Module Pattern.
Module Pattern
The module pattern is a combination of several patterns, namely:
The first step is setting up a namespace. Let’s use the namespace() function from earlier
in this chapter and start an example utility module that provides useful array methods:
The next step is defining the module. The pattern uses an immediate function that will
provide private scope if privacy is needed. The immediate function returns an object – the actual module with its public interface, which will be available to the consumers of
the module:
Next, let’s add some methods to the public interface:
Using the private scope provided by the immediate function, you can declare some
private properties and methods as needed. Right at the top of the immediate function
will also be the place to declare any dependencies your module might have. Following
the variable declarations, you can optionally place any one-off initialization code that
helps set up the module. The final result is an object returned by the immediate function
that contains the public API of your module:
The module pattern is a widely used and highly recommended way to organize your
code, especially as it grows.
“JavaScript Patterns, by Stoyan Stefanov
(O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750