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:
Explanation:
The Outer Function (Factory):
Counter()
acts like a factory, creating and returning a new counter object. Inside it:We declare
count
as our private variable. It's only visible within the scope of theCounter
function.
Return Object: The
Counter
function returns an object containing methods (increment
andgetCount
).Closure Magic: Each method (
increment
,getCount
) is a closure. They "remember" thecount
variable from their surrounding scope (theCounter
function). Even afterCounter()
finishes executing, these methods still have access tocount
.
Why This Works:
When you call
myCounter.increment()
, theincrement
method remembers itscount
and increments it.Similarly, when you call
myCounter.getCount()
, thegetCount
method can read the value ofcount
.
Last updated