How to use Module Pattern in javascript?

Module Pattern in javascript.

Description of javascript module pattern

Modules are an integral part of any robust application’s architecture and typically help in keeping the units of code for a project both cleanly separated and organized. The module pattern is a common JavaScript coding pattern.If you want to understand Module Pattern you should have knowledge about the Closure principle of JavaScript.

Description about closure:

Closures are define through which inner functions can refer to variables present in their outer enclosing function after their parent functions have already terminated.

Here example for closure:


// Below function generates a new function for adding numbers

function generate(number) {

// Return a simple function for adding two numbers

// with the first number borrowed from the generator

return function (toAdd) {

return number + toAdd
};
}

// addFive now contains a function that takes one argument,

// adds five to it, and returns the resulting number

var five_add = generate(5);

// We can see here that the result of the six_add function is 9,

// when passed an argument of 4

alert(five_add(4) == 9);   // Which return true

Example of Module Pattern


var Module_Employee = (function () {
var List_employee = [];
return {
add: function (employee) {
List_employee.push(employee);
},
getAll: function () {
return List_employee;
},
Count: function () {
return List_employee.length;
}
};
})();
We can use our Module_Employee in below way.

Module_Employee.add({ Id: '01', Name: 'Emon Khan', Designation: 'Software Engineer' });
Module_Employee.add({ Id: '02', Name:'Khairul Islam', Designation: 'Senior Software Engineer'});
Module_Employee.getAll();

About the Author

avatar