프로토타입 패턴
JavaScript 프로토타입 패턴
JS에서 객체를 표현하는 5가지 방식과 프로토타입 체인
객체 표현 방식 5가지
1. Object Literal
const healthObj = {
name: "달리기",
lastTime: "PM10:12",
showHealth() {
console.log(this.name + "님, " + this.lastTime + "에 운동하셨네요");
}
}
- 클래스 없이 바로 객체 생성
- 여러 개의 객체를 만들 필요가 없을 때 (일반화 불필요)
2. ES Classes (ES2015~)
const Health = class {
constructor(name, healthTime) {
this.name = name;
this.healthTime = healthTime;
}
showHealth() {
console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
}
}
const ho = new Health("crong", "12:12");
class키워드로 생성자 + 메서드 정의new호출 시constructor자동 실행- 내부적으로 prototype을 사용함
3. Constructor Pattern
const Health = function(name, healthTime) {
this.name = name;
this.healthTime = healthTime;
this.showHealth = function() {
console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
}
}
const ho = new Health("crong", "12:12");
function을new키워드로 호출 → constructor 역할- 메서드가 인스턴스마다 별도 생성 → 메모리 비효율
4. Prototype Pattern
const Health = function(name, healthTime) {
this.name = name;
this.healthTime = healthTime;
}
Health.prototype.showHealth = function() {
console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
}
- 메서드를 prototype 객체에 보관 → 인스턴스들이 메모리 공유
- constructor 패턴보다 메모리 효율 우수
- 여러 인스턴스가 같은 prototype 메서드 주소를 참조
myHealth.__proto__ === myHealth2.__proto__ // true
5. Object.create
const healthObj = {
showHealth() {
console.log(this.name + "님, " + this.healthTime + "에 운동하셨네요");
}
}
const ho = Object.create(healthObj, {
name: { value: "crong" },
healthTime: { value: "12:22" }
})
- prototype 기반 객체 연결(상속)을 명시적으로 표현
- ES6
extends가 더 편리해서 현재는 잘 사용하지 않음
프로토타입 체인
- 모든 객체는 prototype으로 연결되어 있음
- 메서드 호출 시 현재 객체에서 찾고, 없으면
__proto__를 따라 올라감 - 최상위는
Object.prototype
myHealth
├── name: "달리기"
└── __proto__: Health.prototype
├── showHealth: function
└── __proto__: Object.prototype
언제 무엇을 사용하나?
| 상황 | 권장 방식 |
|---|---|
| 단일 객체, 재사용 불필요 | Object Literal |
| 여러 인스턴스 생성 필요 | ES Classes (현대적, 권장) |
| 메모리 최적화 필요 | Prototype Pattern |