so i reached the advanced object section and i have encounter something funny so =
Arrow Functions and this
it seems like we can’t use arrow functions when we use this
because =

so according to this , the arrow function is creates a this
by default , so =
const goat = {
dietType: 'herbivore',
makeSound() {
console.log('baaa');
},
diet: () => {
console.log(this.dietType);
}
};
goat.diet();
Prints undefined , because there are two this
, one .this
and the other is the arrow function
so i thought why not ? let’s delete .this
=

and i got a reference error , but why ?
didn’t we just learned that the arrow function binds an already defined this
, so we have a this
.
that doesn’t make sense (for me)
{i hope you guys understood the question}
Arrow functions bind the this to the function itself, not to the surrounding object. goat is the object, and diet is a method defined within goat. The use of the arrow function syntax means that this will refer to the method, diet. The method, diet, does not have a dietType property. goat does have a dietType property. But the diet method doesn’t have access to the goat’s properties, it only has access to its own properties.
2 Likes
so , is there a way i can use both this
and arrow function ? (at the same time)
Maybe, but if you wanted to mess with binding and this, then you’d be far better off just using traditional function declaration syntax (i.e. function nameOfFunction(arguments) { function body }
). You’d get the added benefit of hoisting too.
3 Likes
Is it possible to use both this and arrow functions concurrently?
In what way? What would you be wanting to do?