7.1 객체 메소드 만들기
JavaScript의 객체 메소드는 객체에 연결되어 그 객체 위에 동작을 수행할 수 있는 함수야. 메소드는 객체가 자기만의 행동을 가질 수 있게 해서 객체 지향 프로그래밍의 중요한 부분을 차지해. 아래에 객체 메소드의 생성과 사용을 살펴보자.
객체 메소드는 여러 가지 방법으로 만들 수 있어. 주요한 방법들을 살펴보자.
1. 객체 리터럴
함수를 사용해서 객체 리터럴 안에 직접 메소드를 만들 수 있어.
이 예제에서 객체 person은 greet() 메소드를 가지고 있어, 이 메소드는 객체의 name 속성을 사용해서 문자열을 반환해:
let person = {
name: 'John',
age: 30,
greet: function() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet()); // 출력: Hello, my name is John
2. 메소드의 축약 문법
ES6부터 객체 메소드 생성에 대한 축약 문법이 생겼어.
이 문법은 코드를 더 간결하고 읽기 쉽게 만들지:
let person = {
name: 'John',
age: 30,
greet() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet()); // 출력: Hello, my name is John
3. 객체 생성 후 메소드 추가하기
메소드는 객체가 생성된 후에 추가될 수 있어.
이 예제에서 메소드 greet()는 객체 person이 생성된 후에 추가돼:
let person = {
name: 'John',
age: 30
};
person.greet = function() {
return `Hello, my name is ${this.name}`;
};
console.log(person.greet()); // 출력: Hello, my name is John
4. 생성자 함수 사용하기
생성자 함수는 모든 객체 인스턴스를 위해 메소드를 만들 수 있게 해줘.
이 예제에서 greet() 메소드는 생성자 함수 Person()로 생성된 모든 객체 인스턴스를 위해 만들어져:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return `Hello, my name is ${this.name}`;
};
}
let john = new Person('John', 30);
let jane = new Person('Jane', 25);
console.log(john.greet()); // 출력: Hello, my name is John
console.log(jane.greet()); // 출력: Hello, my name is Jane
7.2 객체 메소드 사용하기
1. 점으로 메소드 접근하기
객체 메소드는 점 문법을 사용해서 호출할 수 있어:
let person = {
name: 'John',
age: 30,
greet() {
return `Hello, my name is ${this.name}`;
}
};
console.log(person.greet()); // 출력: Hello, my name is John
2. 대괄호로 메소드 접근하기
객체 메소드는 대괄호 문법을 사용해서도 호출할 수 있어:
let person = {
name: 'John',
age: 30,
greet() {
return `Hello, my name is ${this.name}`;
}
};
let result = person['greet']();
console.log(result); // 출력: Hello, my name is John
3. 다른 메소드 안에서 메소드 호출하기
객체 메소드는 동일한 객체의 다른 메소드를 호출할 수 있어.
이 예제에서 sum()와 mul() 메소드는 setValues() 메소드에서 설정된 값을 사용해:
let calculator = {
a: 0,
b: 0,
setValues(a, b) {
this.a = a;
this.b = b;
},
sum() {
return this.a + this.b;
},
mul() {
return this.a * this.b;
}
};
calculator.setValues(2, 3);
console.log(calculator.sum()); // 출력: 5
console.log(calculator.mul()); // 출력: 6
4. 메소드에서 this 사용하기
객체 메소드의 this 키워드는 그 객체 자체를 가리켜, 그 속성이나 다른 메소드에 접근할 수 있게 해줘:
let car = {
brand: 'Toyota',
model: 'Camry',
getInfo() {
return `Brand: ${this.brand}, Model: ${this.model}`;
}
};
console.log(car.getInfo()); // 출력: Brand: Toyota, Model: Camry
5. 메소드를 콜백으로 전달하기
객체 메소드를 콜백으로 전달할 때 this 값에 주의해야 해:
let person = {
name: 'John',
age: 30,
greet() {
console.log(`Hello, my name is ${this.name}`);
}
};
setTimeout( person.greet, 1000 ); // 출력: Hello, my name is undefined
이 예제에서 greet() 메소드가 setTimeout()의 콜백으로 전달될 때 this 값이 사라져버려. 결과적으로 greet() 내부의 this는 전역 객체 window를 가리켜. 브라우저의 window 객체에는 기본적으로 빈 문자열 ""인 name 속성이 있어서 "Hello, my name is"가 출력돼. 올바른 this 값을 유지하려면 bind() 메소드를 사용해서 함수를 특정 컨텍스트에 바인딩할 수 있어:
setTimeout(person.greet.bind(person), 1000); // 출력: Hello, my name is John
또는 화살표 함수를 사용할 수 있어:
setTimeout(() => person.greet(), 1000); // 출력: Hello, my name is John
7.3 메소드 공유 사용
1. 프로토타입을 통한 메소드 상속
메소드는 객체의 프로토타입에 추가되어 모든 인스턴스가 사용할 수 있게 할 수 있어:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function() {
return `Hello, my name is ${this.name}`;
};
let john = new Person('John', 30);
let jane = new Person('Jane', 25);
console.log(john.greet()); // 출력: Hello, my name is John
console.log(jane.greet()); // 출력: Hello, my name is Jane
2. 다른 객체의 메소드 사용하기
한 객체의 메소드는 call() 또는 apply() 메소드를 사용해서 다른 객체에 대해 호출될 수 있어:
let person1 = {
name: 'John',
age: 30,
greet() {
return `Hello, my name is ${this.name}`;
}
};
let person2 = {
name: 'Jane',
age: 25
};
console.log(person1.greet.call(person2)); // 출력: Hello, my name is Jane
GO TO FULL VERSION