Today you will learn:
thisBy the end, you will be able to work efficiently with objects and their methods.
Objects can contain functions as methods:
const user = {
name: "John",
greet() {
return "Hello " + this.name;
}
};
console.log(user.greet()); // Hello John
Explanation:
this refers to the current object (user)Destructuring allows you to extract properties easily:
const user = {
name: "John",
age: 25
};
const { name, age } = user;
console.log(name); // John
console.log(age); // 25
const user = {
name: "John",
greet() {
return "Hello " + this.name;
}
};
console.log(user.greet());
Complete the following:
Example:
const person = {
name: "Alice",
age: 30,
sayHi() {
return "Hi, I am " + this.name;
}
};
// Call the method
console.log(person.sayHi()); // Hi, I am Alice
// Destructuring
const { name, age } = person;
console.log(name); // Alice
console.log(age); // 30