Hello, Guys welcome back today you will know JavaScript Design Patterns. This article provides a summary of the many design patterns in JavaScript that aid in the creation of clean, easier-to-maintain code while without polluting the global namespace.
Object Literal Design Pattern
To avoid collusion with other variables with the same name in the global namespace, group all of your variables and functions into an object with a unique name.
var com = com || {};
com.digitalinspiration = com.digitalinspiration || {};
com.digitalinspiration.person = {
_name: "Amit Agarwal",
_country: "",
setCountry: function (country) {
this._country = country;
},
printCountry: function () {
console.log(this._name + " lives in " + this._country);
},
};
com.digitalinspiration.person.setCountry("India");
com.digitalinspiration.person.printCountry();
Module Design Pattern
Because everything is encased inside an IIFE, this approach can be used to generate private variables in JavaScript that cannot be accessible from the global scope. We write a module that returns an object that contains all of the public functions. Outside of the module, the variables are inaccessible.
var personModule = (function () {
// private variables and methods
var _name = "Amit Agarwal";
var _country = "";
var print = function () {
console.log(_name + " lives in " + _country);
};
return {
setCountry: function (country) {
_country = country;
},
printCountry: function () {
console.log("Calling private method to print " + _country);
print();
},
};
})();
personModule.setCountry("India");
personModule.printCountry();
Module Reveal Pattern
The Reveal Module design pattern facilitates communication between private methods and properties and public methods. Unless explicitly disclosed within the resulting object, all methods and variables are hidden.
var personModule = (function () {
var _name = "Amit Agarwal";
var _interests = [];
function _printInterests() {
console.log(_name + " likes " + _interests.join(", "));
}
function addInterest(interest) {
_interests.push(interest);
}
function printInterests() {
console.log("Calling private method");
_printInterests();
}
return {
printInterests: printInterests,
addInterest: addInterest,
};
})();
personModule.addInterest("Travel");
personModule.addInterest("Reading");
personModule.printInterests();
Avoid the Global Scope
With this section, we conditionally add our module to the global scope and make everything private by enclosing our entire module in an IIFE. The pattern has the advantage of not instantly adding things to the global scope, but rather completing checks to avoid overriding names.
(function (win) {
var personModule = (function () {
var _name = "Amit Agarwal";
function printName() {
console.log(_name);
}
return {
printName: printName,
};
})();
if (!win.personModule) {
win.personModule = personModule;
} else {
throw new Error("Cannot initialize application");
}
})(window);
window.personModule.printName();

