Question about keyword `this` example

Hoping someone can answer this. In the following example to explain the keyword this, it shows that this is added to only one of the two functions in the object. Why does one function require this to work while the other doesn’t? (Example is copied from lesson text in Advanced Objects 2/11 The this Keyword)

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(this.dietType);
  }
};
 
goat.diet(); 
// Output: herbivore

The this is required in the diet method because you’re using the .dietType property of the object. (If the this wasn’t there, it wouldn’t be recognized as this property (value) that’s stored by this object in JavaScript.)

Yes, but why don’t we need this in the makeSound method? Sorry, maybe it wasn’t clear that this is what I was asking. Why one but not the other?

The makeSound function isn’t using any of the enclosing object’s properties. If you had a property called sound, your function might look like this:

const goat = {
  dietType: 'herbivore',
  sound: 'baaa',
  makeSound() {
    console.log(this.sound);
  }
//etc..
}

Right! Thank you, seems obvious now.

1 Like