TIL Closures in Private Methods
POSTED ON:
TAGS: javascript advanced
In JS, closures are useful in hiding the implementation of functionality while still revealing the interface.
Note - it's using a IIFE
For example, imagine you are writing a class of date utility methods and you want to allow users to look up weekday names by index, but you don't want them to be able to modify the array of names you use under the hood.
const jediCatalog = {
getJediFromRank: (function() {
const rankTable = {
"jedi masters" : ["Yoda", "Obi-Wan Kenobi", "Mace Windu"],
"jedi knights" : ["Anakin Skywalker", "Luke Skywalker"],
"padawans" : ["Ahsoka Tano"]
}
return function(x) {
if ((typeof x !== 'string')) {
throw new Error("invalid type. Must be string");
}
if (rankTable.hasOwnProperty(x)) {
return rankTable[x];
} else {
throw new Error("Must be 'jedi masters', 'jedi knights', or 'padawans'")
}
};
}())
};
console.log(jediCatalog.getJediFromRank("jedi masters"));
// result:
// [object Array] (3)
// ["Yoda","Obi-Wan Kenobi","Mace Windu"]
The goal of getJediFromRank
is to get Jedi based on their rank.
Why is rankTable
inside the anonymous function?
It locks the connection of the data to the output, and scopes that data.
A developer can't just modify the jediCatalog
object to change the rankTable. They would have to change it inside the anonymous function, which separates it's concern.
REFERENCE:
https://stackoverflow.com/a/2728628/4096078
SERIES:
- Closure The Basics
- Closure Example with class-like methods
- Closure Example with private data
- Closure Example as a backpack
Related TILs
Tagged: javascript