Use Closure to Protect Properties: intermediate value error

Tell us what’s happening:

I wanted to know why I can’t simply declare a variable getWeight and have it access the variable weight? I get the error: (intermediate value).getWeight is not a function

Why do I get this error?

Your code so far

function Bird() {
  let weight = 15;
  let 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/76.0.3809.100 Safari/537.36.

Link to the challenge:

this.getWeight. if you just declare free variables (let getWeight in Bird), they’re only accessible inside the function. The error is telling you there isn’t a function called getWeight attached to the object that Bird constructs.

This is the point of the exercise: if you use this.weight, then it will be attached to the object created by Bird and will be publicly visible, like the function getWeight is. If you use let weight that’s just a variable that lives in the function Bird. Anything else inside that function can see it, but nothing outside the function can.

function Bird() {
let that=this;

    that.weight = 15;
    that.getWeight = function() {
  let s=0

  var f= new Bird()


That and this is irrelevant was just testing but, closure is basically putting a number in the outer function
like this!

1 Like

the difference is that if you do
var f = new Bird();

and then you try console.log(f.weight); if you used closure to make it a private variable it will tell you it is undefined, otherwise it will give a number

so you use let weight = 15; and then create a function to return the weight, so that f.weigth is undefined

if instead you do this.weight = 15 the property is accessible and changeable from the outside

1 Like

Thank you for the replies, I understand the concept now!

1 Like