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

Tell us what’s happening:
Code works, so that is fine. I’m just wondering if I understood this correctly. I feel I’m a bit lost with the private property.

So let weight = xx; creates a variable inside the constructor, not a property?

If I type in: Bird.weight = 20; and then console.log(Bird.weight); I would be logging the new property named weight, not the variable called weight?

If my logic is correct, isn’t that variable just a plain variable inside an object and not really a property?

Your code so far

function Bird() {
  let weight = 15;
  this.getWeight = function() {
    return weight;
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

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

Link to the challenge:

Right. JavaScript hasn’t always had private properties, so using a variable is the closure of the constructor is an alternative.

Thank you a lot for your reply!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.