I created a variable within the constructor variable, how come that I can still change its value?

Tell us what’s happening:
I passed this challenge and after that, I created a new instance of Bird, I then change the property (weight) to the newly created object. But how come I can still change the weight property even though in the challenge, it says that it supposed to be private?

  **Your code so far**

function Bird() {
let weight = 15;

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

}

let tweet = new Bird();

tweet.weight = 20;

console.log(tweet.getWeight()); //15
console.log(tweet.weight); //20
  **Your browser information:**

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

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

Link to the challenge:

You CANNOT change its value. As the result of tweet.getWeight() shows, the value of weight is still 15.

You CAN change the tweet object though and add properties. And that is exactly what you are doing. You are creating an object tweet which originally has no property weight (you can test this with console.log(tweet.weight) directly after creating tweet); and then you add the property weight to it. Now tweet.weight exists and can be modified. But this is not the same as the internal weight variable that you created with let weight = 15.

1 Like

Just to be clear weight inside the Bird function is not a property, it’s just a local variable. It is scoped to the function and you can not access it directly from outside the function. You can create functions/methods to access it and you can return it out, but you can not get to it from outside the Bird function because it is scoped to the function.

To prevent access to the object you would have to freeze the object or intercept access to it for example using a Proxy.

Random example
function Bird() {
  let weight = 15;

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

let tweet = new Bird();

Object.freeze(tweet);

const tweetProxy = new Proxy(tweet, {
  set: function (oTarget, sKey, vValue) {
    console.log(oTarget, sKey, vValue);
    if (sKey === 'weight') {
      console.log('You are not allowed to add or change this property');
    }
  },
});

tweetProxy.weight = 20;
tweet.weight = 20;

console.log(tweetProxy.getWeight()); // 15
console.log(tweet.getWeight()); // 15
console.log(tweetProxy.weight); // undefined
console.log(tweet.weight); // undefined

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