Object Methods in JavaScript
Object methods are functions stored as properties on objects. They can access and modify the object using the this
keyword.
🛠 Defining Methods
const user = {
name: "Alice",
greet: function() {
return "Hello, " + this.name;
}
};
console.log(user.greet()); // "Hello, Alice"
⚡ ES6 Method Shorthand
const user = {
name: "Bob",
greet() {
return `Hi, I'm ${this.name}`;
}
};
console.log(user.greet()); // "Hi, I'm Bob"
📦 Adding Methods Dynamically
user.sayBye = function() {
return `${this.name} says goodbye.`;
};
console.log(user.sayBye()); // "Bob says goodbye."
🔁 Using this
in Methods
The this
keyword refers to the object the method belongs to.
const car = {
brand: "Tesla",
model: "Model 3",
info() {
return `${this.brand} - ${this.model}`;
}
};
console.log(car.info()); // "Tesla - Model 3"
📚 Built-in Object Methods
Object.keys(obj)
– Returns an array of property namesObject.values(obj)
– Returns an array of property valuesObject.entries(obj)
– Returns an array of [key, value] pairsObject.assign(target, source)
– Copies propertiesObject.freeze(obj)
– Makes object immutable
const obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ["a", "b"]
console.log(Object.values(obj)); // [1, 2]
💡 Tip: Use methods to organize behavior within objects and avoid repeating logic in your code.