Question 43
Question
How would you create a private method using closures?
Answer
Closures are fantastic for achieving "private" methods in JavaScript.
Here's how to do it:
function Counter() {
let count = 0; // Private variable accessible only within the closure
return {
increment: function() {
count++;
},
getCount: function() {
return count;
}
};
}
const myCounter = Counter();
console.log(myCounter.getCount()); // Output: 0
myCounter.increment();
console.log(myCounter.getCount()); // Output: 1Explanation:
The Outer Function (Factory):
Counter()acts like a factory, creating and returning a new counter object. Inside it:We declare
countas our private variable. It's only visible within the scope of theCounterfunction.
Return Object: The
Counterfunction returns an object containing methods (incrementandgetCount).Closure Magic: Each method (
increment,getCount) is a closure. They "remember" thecountvariable from their surrounding scope (theCounterfunction). Even afterCounter()finishes executing, these methods still have access tocount.
Why This Works:
When you call
myCounter.increment(), theincrementmethod remembers itscountand increments it.Similarly, when you call
myCounter.getCount(), thegetCountmethod can read the value ofcount.
Last updated