This Keyword
this = reference to the object where this is used.
(the object depends on the immediate context)
`person.name = this.name`
const person1 = {
name: "Spongebob",
favFood: "hamburgers",
sayHello: function(){console.log(`HI! I am ${this.name}`)},
eat: function(){console.log(`${this.name} loves ${this.favFood}`)}
}
const person2 = {
name: "Patrick",
favFood: "Pizza",
sayHello: function(){console.log(`HI! I am ${this.name}`)},
eat: function(){console.log(`${this.name} loves ${this.favFood}`)}
}
person1.sayHello();
person2.eat();in
()=>{}arrow function,thiswill returnwindowobject
const person1 = {
name: "Spongebob",
favFood: "hamburgers",
sayHello: () => {console.log(`HI! I am ${this.name}`)},
eat: () => {console.log(`${this.name} loves ${this.favFood}`)}
}
person1.eat();
//return " loves undefined"
//this.name = window.name
//this.favFood = window.favFood