Objects in JavaScript can have methods (functions as properties).
They allow objects to perform actions and work with their own data using this
.
🔑 Key Points
- A method is simply a function stored inside an object.
- Use
this
to access properties inside methods. - You can add methods dynamically even after creating an object.
🧩 Examples
1. Defining a method
const user = {
name: "Usama",
age: 22,
greet: function () {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
},
};
console.log(user.greet());
// Hello, my name is Usama and I am 22 years old.
`
2. Adding a method dynamically
`js
user.setAge = function (newAge) {
this.age = newAge;
};
user.setAge(25);
console.log(user.age); // 25
`
3. Checking conditions with a method
`js
user.isAdult = function () {
return this.age >= 18;
};
console.log(user.isAdult()); // true
`
4. Returning details
js
${this.name}, ${this.age} years old.`;
user.getDetails = function () {
return
};
console.log(user.getDetails());
// Usama, 25 years old.
`
📌 Summary
- Methods = functions inside objects.
-
this
= current object reference. - You can create, update, or add methods at any time.
💡 Save this as your cheat sheet and practice often!
What’s your favorite trick with object methods? Drop it in the comments 👇
`
Top comments (0)