The "this" keyword

Could someone explain me why we have to use the “this.dietType” instead of “goat.dietType” in the code below? Both of them work great, so I don’t really understand the need for the “this” keyword.

Thank you

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

Yeah i feel the same, i suppose its useful if you have a nameless object, like you might have if you’re making objects from a function.

1 Like

Objects are their own execution context. this is the property that describes that context for any object. We can create objects with a function (known as factory function) in which case each instance will be assigned its own name. If we hard code a name into the code, its methods can only work on that object.

Using, this permits us to have multiple objects of the same makeup, and invoke methods on each which have access to only the properties of that object.

Likewise, we can define a class of objects (will arise in due course) or we can define a constructor function to create new object instances. No matter the means of object creation, factory, constructor or class, all instances have the same behavior with respect to execution context, through their this property.

2 Likes

I think I am not completely getting it… I mean why not just use goat.dietType in the console.log of diet() (see example)? Is it wrong?

If goat is the only object of this makeup, then go ahead. But if you ever decide you would like to clone this object and assign different values (thereby giving us multiple objects with the same methods and properties, only unique property values) then it will take manual editing to set the execution context. At present this is hard to see, but it will become clear when you get further into the OOP paradigm.

1 Like

Oook makes much more sense now… thank youu!!

1 Like