Object Oriented Programming: Use Closure to Protect Properties Within an Object from Being Modified Externally

function Bird() {
  let hatchedEgg = 10; // private variable
  this.getHatchedEggCount = function() { 
    return hatchedEgg;
  };
}

let ducky = new Bird();

ducky.hatchedEgg = 5;
console.log(ducky.hatchedEgg);

I can change it from the outside. How can it become private? Can anyone explain this?

1 Like

you have added a new property to the object, try with this

console.log(ducky.hatchedEgg);
ducky.hatchedEgg = 5;
console.log(ducky.hatchedEgg);

and you will find it doesn’t have a value before you give it one

try also console.log(ducky.getHatchedEggCount()) and you will see it still returns 10

2 Likes

A post was split to a new topic: Object properties