JavaScript Objects with Methods
Source: Dev.to
What Are Methods in Objects?
A method is a function that lives inside an object. Think of an object like a toolbox, and methods are the tools inside it.
// Object with data and methods (functions inside!)
let person = {
name: "Alice",
age: 25,
sayHello: function() {
console.log("Hello!");
}
};
// Using the method
person.sayHello(); // "Hello!"
Object = Toolbox 🧰
│
├─ Property (data) 📊
├─ Property (data) 📊
├─ Method (function) 🔧
└─ Method (function) 🔧
Example: Account Factory
function createAccount(username, initialBalance) {
let balance = initialBalance;
return {
deposit: function(amount){
balance += amount;
console.log(`Deposited $${amount}. New balance: $${balance}`);
},
withdraw: function(amount){
balance -= amount;
console.log(`Withdrew $${amount}. New balance: $${balance}`);
},
checkBalance: function(){
console.log(`${username}'s balance: $${balance}`);
}
};
}
let account = createAccount("David", 100);
account.deposit(50); // Deposited $50. New balance: $150
account.withdraw(30); // Withdrew $30. New balance: $120
account.checkBalance(); // David's balance: $120
When Defining Methods
❌ Wrong
let obj = {
method(): function() { } // Syntax error!
};
✅ Correct
let obj = {
method: function() { } // Good!
};
The this Keyword
Methods can access other properties in the same object using this:
let person = {
name: "David",
age: 25,
introduce() {
console.log(`Hi! I'm ${this.name} and I'm ${this.age} years old.`);
},
birthday() {
this.age++;
console.log(`Happy birthday! I'm now ${this.age}!`);
}
};
person.introduce(); // Hi! I'm David and I'm 25 years old.
person.birthday(); // Happy birthday! I'm now 26!
person.introduce(); // Hi! I'm David and I'm 26 years old.
Group Related Functions Together
Messy (Separate functions)
function addNumbers(a, b) { return a + b; }
function subtractNumbers(a, b) { return a - b; }
function multiplyNumbers(a, b) { return a * b; }
Clean (Object with methods)
let math = {
add(a, b) { return a + b; },
subtract(a, b) { return a - b; },
multiply(a, b) { return a * b; }
};
math.add(5, 3); // 8
Create Multiple Instances
function createDog(name) {
return {
bark: function() {
console.log(`${name} says: Woof!`);
}
};
}
let dog1 = createDog("Buddy");
let dog2 = createDog("Max");
dog1.bark(); // Buddy says: Woof!
dog2.bark(); // Max says: Woof!
Keep Data Private Using Closures
function createPassword(pwd) {
let password = pwd; // Private variable!
return {
check: function(attempt) {
return attempt === password;
},
change: function(oldPwd, newPwd) {
if (oldPwd === password) {
password = newPwd;
return "Password changed!";
}
return "Wrong password!";
}
};
}
let myPassword = createPassword("secret123");
console.log(myPassword.password); // undefined
console.log(myPassword.check("secret123")); // true
console.log(myPassword.change("secret123", "newPass")); // Password changed!
Method in Object vs. Regular Function
let calculator = {
add: function(a, b) {
return a + b;
}
};
calculator.add(2, 3); // 5 (must call via object)
function add(a, b) {
return a + b;
}
add(2, 3); // 5 (called directly)
Use object methods when functions are related and belong together.
Three Ways to Write Methods
1️⃣ Traditional Way
let calculator = {
add: function(a, b) {
return a + b;
}
};
2️⃣ Shorthand (Modern – Recommended)
let calculator = {
add(a, b) {
return a + b;
}
};
3️⃣ Arrow Function
let calculator = {
add: (a, b) => {
return a + b;
}
};
Calling Methods
let obj = {
method() {
console.log("Called!");
}
};
obj.method; // Returns the function (does not call it)
obj.method(); // Calls the function ✓
Happy coding!