@manhng

Welcome to my blog!

JavaScript Module Pattern

July 24, 2017 10:27

JavaScript Design Patterns

1) Module and Revealing Module Patterns in JavaScript
Dheeraj Kumar Kesri, 5 Jan 2017

https://www.codeproject.com/Articles/1164113/Module-and-Revealing-Module-Patterns-in-JavaScript

 

2) Javascript design patterns and IIFE
Rajiv Gogoi, 21 Sep 2014

https://www.codeproject.com/Articles/819565/Javascript-design-patterns-and-IIFE

 

3) JavaScript Design Patterns
Nitin Singh India, 4 Sep 2013

https://www.codeproject.com/Articles/636699/JavaScript-Design-Patterns

 

4) The JavaScript Module Pattern With jQuery
Troy W. Locke, 10 Feb 2016

https://www.codeproject.com/Tips/1077599/The-JavaScript-Module-Pattern-With-jQuery

 

5) Module Pattern in JavaScript in Depth
Emon Khan, 26 Jul 2013

https://www.codeproject.com/Articles/619747/Module-Pattern-in-JavaScript-in-Depth

 

6) JavaScript Module Pattern

Rupesh Kumar Tiwari, 25 Apr 2013

https://www.codeproject.com/Articles/247241/Javascript-Module-Pattern

JavaScript Module Pattern

DOMContentLoaded

https://developer.mozilla.org/en/docs/Web/Events/DOMContentLoaded

Immediately Invoked Function Expressions (IIFE)

Source Code

<!DOCTYPE html>
<html>
<head>
<script>
var Mathlibrary = function(){
// private count variable
var count = 0;

// private method _add
var _add = function(a, b){
count++;
var total = a+b;
document.writeln(a + "+" + b+ "= " + total + " (count = " + count + ")<br />");
};

// private method _sub
var _sub = function(a, b){
count++;
var sub = a-b;
document.writeln(a + "-" + b+ "= " + sub + " (count = " + count + ")<br />");
}

// return public method add and sub as a JavaScript
// Object literal
return{
add : _add,
sub : _sub
}
}();
</script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
// As its a singleton, we don't need to create an object but can directly call the methods.
Mathlibrary.add(150,100);
Mathlibrary.sub(150,100);
});
</script>
</head>
<body>
</body>
</html>

Categories

Recent posts