프로토타입 예제
function Animal (name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + " makes a sound.");
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(this.name + " barks.");
};
const dog = new Dog("Mimi");
dog.speak();
dog.bark();
console.log(dog.constructor);
Dog.prototype.constructor = Dog; 가 필요한 이유
Animal.prototype.constructor은 Animal을 가리킴
따라서 Dog.prototype = Object.create(Animal.prototype);을 실행하면, Dog.prototype이 Animal.prototype을 상속하는 새로운 객체가 되어 constructor가 Dog가 아니라 Animal이 되기 때문
Q. 왜 Animal이 아니라 Animal Prototype에 메서드를 추가하는지?
1. Animal에 직접 메서드를 추가하면?
만약 Animal 생성자 함수 내부에서 메서드를 추가한다면, 이렇게 될 거야:
function Animal(name) {
this.name = name;
this.speak = function() { // ❌ 비효율적인 방식
console.log(this.name + " makes a sound.");
};
}
const cat1 = new Animal("Kitty");
const cat2 = new Animal("Tom");
console.log(cat1.speak === cat2.speak); // false ❌ (각 인스턴스마다 새로운 함수가 생성됨)
문제점
- speak 메서드가 각 인스턴스마다 새롭게 생성됨.
- 즉, cat1과 cat2는 각각 다른 speak 함수를 가짐 (메모리 낭비).
- 만약 speak 메서드를 수정하려면?
- 모든 인스턴스에 각각 새로운 메서드를 설정해야 함 (유지보수가 어려움).
2. Animal.prototype에 메서드를 추가하면?
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() { // ✅ 효율적인 방식
console.log(this.name + " makes a sound.");
};
const cat1 = new Animal("Kitty");
const cat2 = new Animal("Tom");
console.log(cat1.speak === cat2.speak); // true ✅ (모든 인스턴스가 같은 함수를 공유)
장점
- 모든 인스턴스가 같은 메서드를 공유함 (메모리 절약).
- cat1.speak과 cat2.speak가 같은 함수임 (true 반환).
- 메서드를 한 번만 정의하면 됨.
- prototype에 있는 메서드를 수정하면 모든 인스턴스가 즉시 변경 사항을 반영할 수 있음.
3. 메서드는 프로토타입에 추가하는 게 원칙!
JavaScript에서 생성자 함수 패턴을 사용할 때, 공유해야 하는 메서드는 prototype에 추가하는 게 원칙이야.
✅ 인스턴스별로 고유한 속성(예: name)은 this에 추가하고,
✅ 공유해야 하는 메서드(예: speak())는 prototype에 추가하는 게 최적의 방식이야.
4. 프로토타입 체인과 실행 과정
const cat = new Animal("Kitty");
cat.speak();
이 코드가 실행될 때, JavaScript는 프로토타입 체인을 통해 speak() 메서드를 찾음.
- cat.speak()를 호출하면,
- cat 객체 안에서 speak 메서드를 찾음 → 없음.
- cat.__proto__ (즉, Animal.prototype)에서 speak를 찾음 → 발견됨!
- speak()를 실행!
즉, prototype을 이용하면 JavaScript의 상속 메커니즘을 활용해서 불필요한 메서드 중복을 방지할 수 있어.
5. 결론
✔️ 인스턴스마다 다른 값이 필요한 속성 → this.name처럼 this에 저장해야 함.
✔️ 모든 인스턴스가 공유할 메서드 → Animal.prototype에 저장해야 메모리를 절약하고 유지보수가 편리해짐.
✔️ JavaScript의 프로토타입 체인을 활용하면 불필요한 중복을 피할 수 있음. 🚀
'HANCOM AI ACAMEMY > 수업 및 플젝' 카테고리의 다른 글
| React Native : API 요청 (0) | 2025.03.12 |
|---|---|
| React Native : 3월 10일 (0) | 2025.03.10 |
| Javascript : 2월 12일 (0) | 2025.02.12 |
| Javascript : 2월 11일 (0) | 2025.02.11 |
| Javascript : 2월 10일 (0) | 2025.02.10 |
댓글