Middle
How can encapsulation be implemented in JavaScript using closures?
sobes.tech AI
Answer from AI
Encapsulation in JavaScript can be implemented using closures, creating private variables and methods inside a function that are inaccessible from outside but can be used by functions declared within.
function createCounter() {
let count = 0; // Private variable
return {
increment: function() { // Public method
count++;
console.log(count);
},
decrement: function() { // Public method
count--;
console.log(count);
},
getCount: function() { // Public method
return count;
}
};
}
const counter = createCounter();
counter.increment(); // Output: 1
counter.increment(); // Output: 2
console.log(counter.getCount()); // Output: 2
// console.log(counter.count); // undefined - access to private variable is forbidden
In this example:
countis a private variable accessible only to functions declared insidecreateCounter.- The object returned by the function contains public methods (
increment,decrement,getCount) that have access to the private variablecountthanks to closure. - From outside, we can only call these public methods on
counter, but cannot directly access or modifycount.
This allows hiding the internal state of the object and providing a controlled interface for interaction.