Modules &
Design Patterns
What is a Module?
Sections of code which can be moved, removed or added without disrupting the system as a whole (keeps code organized and separated)
The benefits of using modules
-
Maintainability - Lessens the dependency on other parts of the codebase
-
Namespacing - Unrelated code shares global variables
-
Reusability - Ability to reuse modules
How to use modules?
- By using a the module pattern which is a design pattern.
- A design pattern is used to describe a common approach to solving a programming task.
- The module pattern is a popular way to write code that contains both public and private logic
IIFE
- An IIFE runs as soon as it is defined
- The function is executed once as the interpreter comes across them
- Used for code that only needs to run one within a task
- Commonly used as a wrapper around a set of code
Module patterns uses an IFFE (Immediately Invoked Function Expression) to return an object
Anonymous Closure
(function(){
//salaries are private
var salaries = [1000, 2000, 5000, 7000, 10000];
var avgSalary = function(){
var total = 0;
for(var i = 0; i<salaries.length; i++){
total += salaries[i];
var avg = total/salaries.length;
}
return avg;
}
console.log(avgSalary()); //5000
}());
- Hides variables (local) from the global scope
- A closure is where an inner function has access to the outer
- Enclosing function's variables
The Object Interface
var workerSalaries = (function(){
var salaries = [10, 20, 30, 40, 50];
return {
median: 30,
maxSalary: function(){
var max = Math.max(salaries[0], salaries[4]);
return max;
}
}
}()); //50
- Self contained object
- The variable is kept private inside the closure scope
- returns an object that can be accessed
The Module Pattern
var openBank = (function(){
//private
var name = 'Jon Smith';
var acctNo = 12345;
var obj = {};
//public var
obj.balance = 300000;
//public method
obj.deposit = function(n){
var newBal = this.balance + n;
return newBal
}
return obj;
}())
console.log(openBank.balance)
console.log(openBank.deposit(1))
console.log(openBank.acctNo)
- Create the object to be returned
The Revealing Module Pattern
var workerSalaries = (function(){
var salaries = [10, 20, 30, 40, 50];
var maxSalary = function(){
var max = Math.max(salaries[0], salaries[4]);
return max;
}
return {
maxSalary: maxSalary
}
}())
console.log(workerSalaries.maxSalary()) //50
- Ensures that all variables and methods are kept private
- Must be explicitly exposed to the public in the return object
- Most popular of all the module patterns
Modules
By vic_lee
Modules
- 465