I get lost, here i can access the private variable and change it outside the context of the function; so how it's called private in this way?

Tell us what’s happening:

Your code so far


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

}

let bird = new Bird();

console.log(bird.weight)

Your browser information:

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

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

Link to the challenge:

Hey, Ali,

You can’t access the weight private variable outside of the closure in this way. Instead, you need to access it using the getter function getWeight(). If you wanna modify it, you should create a setter function that sets the private variable. If you try to modify the variable without a setter, this won’t affect the variable in the closure. Because the closure takes a copy of that variable, so it can’t be modified from outside the function.

So, your code should be as follows

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

}

let bird = new Bird();

console.log(bird.getWeight())
1 Like