Reputation: 1035
I've been studying javascript just now and i'm currently in closures. It is said that closure emulates private variables. But aren't variables only accessible on their own scope making them private by default? Given this example
function manageSalary () {
let salary = 0;
function updateSalary(amount) {
salary += amount;
}
return {
raise: function(amount) {
updateSalary(amount);
},
deduct: function(amount) {
updateSalary(amount);
},
current: function () {return salary}
}
};
How exactly does closure makes the salary variable private in this example? Isn't salary already private since you cant access it outside this manageSalary? What I understood from this example rather is that closure emulates private methods instead.
Upvotes: 1
Views: 30
Reputation: 1074829
Tackling your questions slightly out of order:
Isn't salary already private since you cant access it outside this manageSalary?
Yes.
How exactly does closure makes the salary variable private in this example?
The closures don't make salary
private. As you said, it's already private. The closures take advantage of the fact salary
is private but they (the closures) aren't. The return value of manageSalary
is an object with those closures on it as (effectively) methods. The methods have access to salary
, but nothing else has access to it.
Upvotes: 2