Javascript Syntax II - Objects - Meal Maker Project - 'This' keyword

Hello! I was hoping that someone could explain this to me. I just finished this assignment, but I ran into a few errors. which I understood that one of them was that I did not reference the properties in the menu object correctly (Appetizers, mains, and desserts). However, my last mistake needed a ‘this’ keyword to reference the generateRandomMeal function. Why is that? Is it a scoping issue?

generateRandomMeal() {
const appetizer = this.getRandomDishFromCourse(‘appetizers’)
const main = this.getRandomDishFromCourse(‘mains’)
const dessert = this.getRandomDishFromCourse(‘desserts’)
const totalPrice = appetizer.price + main.price + dessert.price;

return Your meal will be ${appetizer.name}, ${main.name}, and ${dessert.name}. Your bill is $${totalPrice}.;
}

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

Sort of. this. is the encapsulating object, in which the method is contained. Without referencing the method as a property of the object, we end up referencing the global window object. There is no such function (method) associated with that object.

1 Like

So basically, I need to use the keyword “This.” when I need to reference methods inside object because not doing so means that I would be trying to reference methods outside the object? which would be the wrong way to try to interpret it.

1 Like

As it stands, yes. It would be a real toss up if there was actually a function with the same name. It would execute and we’d be none the wiser unless the result was not as expected. this gives execution context as being within the object.

1 Like