Why do Arrow functions exist and how could you use them in objects if you wanted to?

Ok, I understand that Arrow Functions cannot be used for when we use the ‘this’ keyword for accessing properties inside the calling object. However, I don’t understand what is this ‘global object’ that the arrow function is calling instead of the calling function. In terms of the example below, WHICH would be the global object? They didn’t specify what is the global object’s physical form in an example.

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

goat.diet(); // Prints undefined

Just before that line, insert,

dietType = 'omnivore'

Now run it.

1 Like

Below code still prints undefined instead of omnivore.
Why is that?

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

dietType = 'omnivore';
goat.diet();
goat.dietType = ...

Below still prints undefined:

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

goat.dietType = 'omnivore';
goat.diet(); // undefined

It only prints omnivore when not declared by an arrow function:

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

goat.dietType = 'omnivore';
goat.diet(); // omnivore

Doesn’t this in the arrow function refer to the global goat.dietType = 'omnivore';?

Remove the colon as indicated.

Result:

  diet () => {
          ^^

SyntaxError: Unexpected token '=>'

I’m pretty confused…

Oh I think I get it… Is it that when using arrow function inside an object like below,

diet: () => {
    console.log(this.dietType);
}

this refers to global.dietType / window.dietType but not goat.dietType and therefore returns undefined?

So even if goat.dietType is defined outside the object (const goat) at a global scope it still wouldn’t work. Am I correct?

The correct form of a methdod is,

diet () {

}
1 Like