The module pattern is an object-creation pattern designed to create singleton objects with private data. The basic approach is to use an immediately invoked function expression (IIFE) that returns an object. An IIFE is a function expression that is defined and then called immediately to produce a result. That function expression can contain any number of local variables that aren’t accessible from outside that function. Because the returned object is defined within that function, the object’s methods have access to the data. Methods that access private data in this way are called privileged methods.
Here’s the basic format for the module pattern. In this pattern, an anonymous function is created and executed immediately. (Note the extra parentheses at the end of the function. You can execute anonymous functions immediately using this syntax.) That means the function exists for just a moment, is executed, and then is destroyed.
var yourObject = (function() {
// private data variables
return {
// public methods and properties
};
}());
The below code creates the person object using the module pattern. The age variable acts like a private property for the object. It can’t be accessed directly from outside the object, but it can be used by the object methods. There are two privileged methods on the object: getAge(), which reads the value of the age variable, and growOlder(), which increments age. Both of these methods can access the variable age directly because it is defined in the outer function in which they are defined.
var person = (function() {
var age = 25;
return {
name: "Nicholas",
getAge: function() {
return age;
},
growOlder: function() {
age++;
}
};
}());
console.log(person.name); // "Nicholas"
console.log(person.getAge()); // 25
person.age = 100;
console.log(person.getAge()); // 25
person.growOlder();
console.log(person.getAge()); // 26
Revealing Module Pattern
There is a variation of the module pattern called the revealing module pattern, which arranges all variables and methods at the top of the IIFE and simply assigns them to the returned object. You can write the previous example using the revealing module pattern as follows:var person = (function() {
var age = 25;
function getAge() {
return age;
}
function growOlder() {
age++;
}
return {
name: "Nicholas",
getAge: getAge,
growOlder: growOlder
};
}());
In this pattern, age, getAge(), and growOlder() are all defined as local to the IIFE. The getAge() and growOlder() functions are then assigned to the returned object, effectively "revealing" them outside the IIFE.
Source: The principles of object-oriented JavaScript by Nicholas
Reference: https://coryrylan.com/blog/javascript-module-pattern-basics
0 comments:
Post a Comment