Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why module pattern?

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 ?

like image 388
Stef Avatar asked Sep 19 '11 13:09

Stef


People also ask

Why is it important to use the module pattern in JavaScript?

The Module pattern is used to mimic the concept of classes (since JavaScript doesn't natively support classes) so that we can store both public and private methods and variables inside a single object — similar to how classes are used in other programming languages like Java or Python.

What is modular design pattern?

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.

When would you use the revealing module pattern?

The Revealing Module pattern can easily imitate either the Class Pattern or the Namespace Pattern with the added advantage of private state and private functions. This is most helpful in Scoped Applications where the app developer may prefer to keep implementation details hidden while exposing clear public interfaces.

What is module pattern in node JS?

What is Module Pattern? The module pattern is a special Design pattern in which we use IFFI (Immediately invoked function expression), and we return an object. Inside of that object, we can have functions as well as variables.


2 Answers

I think this example could help you to clarify the usefulness of the Module Pattern.

Module Pattern

The module pattern is widely used because it provides structure and helps organize your code as it grows. Unlike other languages, JavaScript doesn’t have special syntax for packages, but the module pattern provides the tools to create self-contained decoupled pieces of code, which can be treated as black boxes of functionality and added, replaced, or removed according to the (ever-changing) requirements of the software you’re writing.

The module pattern is a combination of several patterns, namely:

  • Namespaces
  • Immediate functions
  • Private and privileged members
  • Declaring dependencies

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:

MYAPP.namespace('MYAPP.utilities.array');

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:

 MYAPP.utilities.array = (function () {
    return {
    // todo...
    };
 }());

Next, let’s add some methods to the public interface:

MYAPP.utilities.array = (function () {
   return {
      inArray: function (needle, haystack) {
         // ...
      },
      isArray: function (a) {
         // ...
      }
   };
}());

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:

MYAPP.namespace('MYAPP.utilities.array');
MYAPP.utilities.array = (function () {
   // dependencies
   var uobj = MYAPP.utilities.object,
       ulang = MYAPP.utilities.lang,
       // private properties
       array_string = "[object Array]",
       ops = Object.prototype.toString;
       // private methods
       // ...
       // end var
   // optionally one-time init procedures
   // ...
   // public API
   return {
      inArray: function (needle, haystack) {
         for (var i = 0, max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
               return true;
            }
         }
      },
      isArray: function (a) {
         return ops.call(a) === array_string;
      }
      // ... more methods and properties
   };
}());

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

like image 130
user278064 Avatar answered Oct 14 '22 08:10

user278064


Not sure why no one's answered this one properly. I can see potential for using auto-invoking functions in some kind of pattern meant to make private vars inheritable, but you're absolutely right.

There is no benefit to using the module pattern in place of a core language function constructor. It's the same exact language mechanic (closures) that allows the persistent internal vars to exist as non-accessible entities only with more code.

In JS a function constructor follows the same rules of scope as a fired function. Scope and closure is set at point of definition. The reason the internal var from a function constructor lives on is because the instance with methods defined inside the same constructor referencing that var lives on.

The only thing that changes is that you've eliminated the use of prototyped methods on the constructor and have to jury-rig your own inheritance mechanism for inherited methods.

like image 39
Erik Reppen Avatar answered Oct 14 '22 07:10

Erik Reppen