Understanding how to use "The this Keyword." [ref: Meal Maker Exercise]

Greetings, I wish to know exactly what the “The this Keyword” works in the context of objects inside objects and so on. does the this keyword take us back to the parent object or it just ups us one level.

Here is what I mean

I make it a habit of watching the walkthroughs even when I am able to complete a exercise on my own. now in the meal maker exercise, the instructor sets the getter function of the appetizers as return as `return this._courses.appetizers;
his view something like this .

const menu = {
  _courses: {
    appetizers: [1,2,3],
    mains: [],
    desserts: [],
    get appetizersGet(){
        return this._courses.appetizers;
				
}
}
}

when I try this and log menu._courses.appetizersGet it gives an error.

But when I format code such that the getter function returns return this.appetizers

that is …

const menu = {
  _courses: {
    appetizers: [1,2,3],
    mains: [],
    desserts: [],
    get appetizersGet(){
        return this.appetizers;
}
}
}
		
		```

console logging `menu._courses.appetizersGet` gives me the values of the appetizers array.


so my questions is, how did his work? does the this up you just one level when working with objects in objects or does it  take you to the "parent most" object .

will appreciate someone clearing this up for me.

Hi there!

I think the this keyword always point to the object where is defined. You are using “this” inside the _courses object since the get method is inside _courses object, so it points to _courses even although _courses is an object inside another object. In your first example I’d say what you are doing is: “return _courses._courses.appetizers.” You are trying to return an appetizers key inside a _course object which is at the same time inside another _course object and it doesn’t exist.

1 Like

this is the execution context, the parent object, _courses. Given the method is within the same parent object, we refer to sibling properties in this context.

1 Like

Sorry I’m still confused somehow, so what those this do exactly?

The difference is that in the picture the get method is defined in the menu object and in your first message the get method was defined in _courses object.

So in this case “this” is equivalent to “menu” so you are returning menu._courses.appetizers.

1 Like

Thank you, makes sense now.