Tell us what’s happening:
How do you change the variable hatchedEgg in the below example? I understand the idea that you need to make a private variable so it can’t be changed on accident, but what if you want to be able to change it?
**Your code so far**
function Bird() {
let hatchedEgg = 10;
this.getHatchedEggCount = function() {
return hatchedEgg;
};
}
let ducky = new Bird();
ducky.getHatchedEggCount();
Challenge: Use Closure to Protect Properties Within an Object from Being Modified Externally
You set and get the data from inside the function scope using functions/methods you control. The user of the API can still interact with the data just not without using your API (i.e. the methods you have in place for interacting with the data).
The point is no direct access to the data is allowed from the outside.
No, you create a method that can be called on the instance which allows the user to change it. The internal logic controls how they can, or can’t change it.
function Bird() {
let hatchedEgg = 10;
this.getHatchedEggCount = function () {
return hatchedEgg;
};
this.setHatchedEggCount = function (count) {
if(count < 1) return;
hatchedEgg = count;
};
}
let ducky = new Bird();
console.log(ducky.getHatchedEggCount()); // 10
ducky.setHatchedEggCount(5);
console.log(ducky.getHatchedEggCount()); // 5
ducky.setHatchedEggCount(0);
console.log(ducky.getHatchedEggCount()); // 5