Gettters & Setters Sharing Names with Properties

In the Advanced Object lessons, in the Getter unit:
“Another thing to keep in mind when using getter (and setter) methods is that properties cannot share the same name as the getter/setter function.”

However in the Meal Maker project the solution uses the same name for getter/setter function as the property of the menu_courses object. the properties appetizers, mains, desserts.

I thought that would create infinite stack call error, but looks like I don’t understand.

Depends how you implement the getters and setters, if you do this:

const menu = {
  _courses: {
     appetizers: [],
  },
  get appetizers(){
     return this._courses.appetizers;
  }
}

and you do:

console.log(menu.appetizers)

you are good.

menu.appetizers will trigger/invoke the getter, which will then access _courses property (no getter), so that goes fine. then within the courses object, the appetizers property is accessed. This property doesn’t have a getter, so you are good

I have seen problematic variants like:

const menu = {
   _courses: {
    mains: {}
  }
  get _courses(){
    return this._courses.mains;
  }
}

which is problematic, the getter and property share the same name, and within the getter we use the getter. The getter for courses shouldn’t have an underscore here

or this variant:

const menu = {
   _courses: {
    mains: {}
    get mains{
        return this.mains;
     }
  }
}

these are all problematic because the getter ends up calling the getter. In this example, the mains property would need an underscore:

_mains: {}
get mains() { return this._mains }

then all things are good :slight_smile: