Confuse of Use Closure to Protect Properties Within an Object from Being Modified Externally

Tell us what’s happening:
I inserted the code following the guide, but I don’t understand how by creating a variable within the constructor function works on making the public property private.

  **Your code so far**

function Bird() {
let weight = 15;

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

let ducky = new Bird();
ducky.getWeight();
  **Your browser information:**

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

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

Link to the challenge:

there is no way to access or change the weight variable from outside the object, so it can be considered private

1 Like

Like @ILM said - you can’t access the weight variable directly like this, you have to use the getter function.

console.log(ducky.weight) //undefined

It makes a difference whether you define a variable inside the function, or declare a property like this:

function Bird() {
  let weight = 15;
  this.height = 20;
}

console.log(ducky.height) // 20
ducky.height = 30;
console.log(ducky.height) // 30
1 Like

Thanks ilenia, appreciate for the advice.

Thanks @jsdisco for the detailed explanation!

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