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
mtf
November 4, 2021, 6:57pm
23
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();
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';
?
mtf
April 21, 2022, 1:34am
27
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?
mtf
April 21, 2022, 4:40pm
31
The correct form of a methdod is,
diet () {
}
1 Like