What Are Methods in Objects?
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!"
See? sayHello is a method - it's a function inside the object!
Visual Example
Object = Toolbox π§°
β
ββ Property (data) π
ββ Property (data) π
ββ Method (function) π§
ββ Method (function) π§
Usage: toolbox.method()
Real-Life Example
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(`Alice'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"
Important: NO () When Defining!
β WRONG:
let obj = {
method(): function() { } // Syntax error!
};
β CORRECT:
let obj = {
method: function() { } // Good!
};
Using 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."
Why Use Methods in Objects?
β Organization
Group related functions together:
// β Messy
function addNumbers(a, b) { return a + b; }
function subtractNumbers(a, b) { return a - b; }
function multiplyNumbers(a, b) { return a * b; }
// β
Clean
let math = {
add(a, b) { return a + b; },
subtract(a, b) { return a - b; },
multiply(a, b) { return a * b; }
};
math.add(5, 3); // Much cleaner!
β Reusability
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!"
β Data Privacy
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 - can't access directly!
console.log(myPassword.check("secret123")); // true
console.log(myPassword.change("secret123", "newPass")); // "Password changed!"
Quick Comparison
Method in Object vs Regular Function
Object Method:
let calculator = {
add: function(a, b) {
return a + b;
}
};
calculator.add(2, 3); // Must use object.method() => calculator.___
Regular Function:
function add(a, b) {
return a + b;
}
add(2, 3); // Call directly
Use object methods when functions are related and belong together!
How to Define Methods
There are 3 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;
}
};
Common Mistakes
β Mistake 1: Adding () when defining
let obj = {
method(): function() { } // Wrong!
};
β Mistake 2: Forgetting () when calling
obj.method; // Returns the function, doesn't call it!
obj.method(); // Calls the function β
β Mistake 3: Wrong template literal syntax
console.log`Hello`; // Wrong!
console.log(`Hello`); // Correct!
Happy Coding...!
Found this helpful? Give it a β€οΈ!
Top comments (0)