📌 What Are Object Methods?
In JavaScript, object methods are functions stored as properties of objects. These methods allow objects to perform actions or manipulate their own data. 🚀
Since functions are first-class citizens in JavaScript, you can assign them to object properties just like any other value.
🧪 Basic Example
Defining an Object Method
const user = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name + "!");
}
};
user.greet(); // Hello, Alice!Here, greet is a method of the user object. The this keyword refers to the current object — user. 🧠
📦 Shorthand Syntax
Method Shorthand
const user = {
name: "Alice",
greet() {
console.log("Hi, " + this.name + "!");
}
};
user.greet(); // Hi, Alice!ES6 introduced a more concise way to define methods using method shorthand. It makes object declarations cleaner and easier to read. ✨
🪞 Using this in Methods
The this keyword inside an object method refers to the object itself. It's commonly used to access or modify the object’s properties from within its own methods.
Note
Arrow Function Pitfall
const user = {
name: "Bob",
greet: () => {
console.log("Hi, " + this.name); // undefined
}
};
user.greet();🧪 Methods That Modify Object Properties
Changing Property Values
const counter = {
value: 0,
increment() {
this.value++;
}
};
counter.increment();
console.log(counter.value); // 1The method increment() changes the object's internal value property by using this. 🔁
🧠 Dynamic Method Assignment
Assign Method Later
function sayHi() {
console.log("Hi!");
}
const person = {};
person.greet = sayHi;
person.greet(); // Hi!Methods can be assigned after object creation — even from external function definitions. This showcases JavaScript’s flexibility. 🧩
✅ Summary
- Object methods are functions stored as object properties
- this refers to the object the method belongs to
- Use method shorthand for cleaner syntax
- Avoid arrow functions if you need this inside the method
- Methods can be added or reassigned dynamically