Methods often need to use the other properties of their own object. For example, a method that introduces a person needs to know that person's name. Inside a method, the special keyword this refers to the object the method belongs to:
const person = {
firstName: "Sofia",
lastName: "Rossi",
age: 24,
introduce() {
console.log(`Hi, I'm ${this.firstName} ${this.lastName} and I'm ${this.age}.`);
},
haveBirthday() {
this.age++;
console.log(`🎂 Happy birthday! ${this.firstName} is now ${this.age}.`);
},
};
person.introduce();
person.haveBirthday();
person.introduce();
It prints
Hi, I'm Sofia Rossi and I'm 24. 🎂 Happy birthday! Sofia is now 25. Hi, I'm Sofia Rossi and I'm 25.
When we call person.introduce(), this means person, so this.firstName means person.firstName. Think of this as the object saying "my first name," "my age."
Arrow functions don't get their own this. They borrow it from the code around them. So if you use an arrow function as a method, this won't point at your object:
const cat = {
nickname: "Whiskers",
speak: () => {
console.log(`Meow, I am ${this.nickname}`);
},
};
cat.speak();
It stops with an error
Uncaught TypeError: Cannot read properties of undefined (reading 'nickname')
Here this is undefined, so this.nickname crashes. (In a browser's console you may see Meow, I am undefined instead.) Either way, this isn't the cat. Use a regular method (speak() { ... }) whenever you need this. The full story of this is a bit of an adventure, and we'll go on it properly in College.