I was learning about lexical this
in ES6, and I countered this example :
let person = {
name : 'Alex',
cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
toString : function(){
for(let car of cars){
console.log(`${this.name} has ${car}`)
}
}
}
person.toString();
so let's say I want to convert the toString function to an array function so I'll have this :
let person = {
name : 'Alex',
cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
toString : () => {
for(let car of cars){
console.log(`${this.name} has ${car}`)
}
}
}
person.toString();
in this example cars
is undefined, why I'm getting that, and how can I call cars
from the person
object in that example.
the same goes for this :
let person = {
name : 'Alex',
cars : ['Ferrari','Jaguar','Bugatti','Cadillac'],
toString : () => {
cars.forEach(car => console.log(`${this.name} has ${car}`));
}
}
person.toString();