Why does a method that calls an object within a main object not work?

In this lesson, a new method of diet() that calls the dietType object does not work.

Why does it not work except with the use of the this keyword?

I believe you are referring to this example code:

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(dietType);
  }
};
goat.diet(); 
// Output will be "ReferenceError: dietType is not defined"

The explanation is bit below:

The this keyword references the calling object which provides access to the calling object’s properties

Yes, I am.

Would it be correct to say that the diet() child method has a different scope from its parent object of goat?

Hence, to access a property of the parent object of goat from within a child method of diet() , you will have to use the this keyword?

Is this correct?

Yeah, it is useful to think about it in terms of scope.

this is actually complicated and takes different forms depending on where it is used. For a deeper dive, I recommend that you take a look at this article A guide to this in JavaScript | freeCodeCamp

1 Like

Scope relates to namespace, whereas this relates to execution context.

const y = x => x ** 3

this.y(5)    //  125

The execution context of y is the window object.

maths = {
    y = 5,
    cube () {
      return this.y ** 3
    }
}

maths.cube()    //  125

Nothing practical about that, but the main gist is the different execution context, the maths object.

1 Like