JavaScript 객체와 메서드
발행: (2026년 2월 4일 오후 02:52 GMT+9)
4 min read
원문: Dev.to
Source: Dev.to
객체의 메서드란 무엇인가?
메서드는 객체 내부에 존재하는 함수입니다. 객체를 도구 상자에 비유하면, 메서드는 그 안에 들어있는 도구와 같습니다.
// 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 = 도구 상자 🧰
│
├─ 속성 (데이터) 📊
├─ 속성 (데이터) 📊
├─ 메서드 (함수) 🔧
└─ 메서드 (함수) 🔧
예시: 계정 팩토리
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
메서드 정의 시
❌ 잘못된 예
let obj = {
method(): function() { } // Syntax error!
};
✅ 올바른 예
let obj = {
method: function() { } // Good!
};
this 키워드
메서드는 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(); // 안녕! 나는 David이고 나는 25살이야.
person.birthday(); // 생일 축하해! 이제 나는 26살이야!
person.introduce(); // 안녕! 나는 David이고 나는 26살이야.
그룹 관련 함수들을 함께 묶기
지저분함 (별도 함수)
function addNumbers(a, b) { return a + b; }
function subtractNumbers(a, b) { return a - b; }
function multiplyNumbers(a, b) { return a * b; }
깔끔함 (메서드가 있는 객체)
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
여러 인스턴스 만들기
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!
클로저를 사용하여 데이터 비공개 유지
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!
Object 메서드 vs. 일반 함수
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)
함수들이 서로 관련이 있고 함께 묶여 있을 때 객체 메서드를 사용하세요.
메서드를 작성하는 세 가지 방법
1️⃣ 전통적인 방법
let calculator = {
add: function(a, b) {
return a + b;
}
};
2️⃣ 축약형 (모던 – 권장)
let calculator = {
add(a, b) {
return a + b;
}
};
3️⃣ 화살표 함수
let calculator = {
add: (a, b) => {
return a + b;
}
};
메서드 호출
let obj = {
method() {
console.log("Called!");
}
};
obj.method; // 함수를 반환합니다 (호출되지 않음)
obj.method(); // 함수를 호출합니다 ✓
행복한 코딩 되세요!