프로토타입과 상속 (Prototype & Inheritance)
🧬 프로토타입 (Prototype)이란?
자바스크립트는 프로토타입 기반(Prototype-based)의 객체지향 언어입니다. C++나 Java처럼 클래스(Class)라는 설계도를 통해 객체를 생성하는 대신, 기존에 존재하는 어떤 객체(Prototype)를 원형(유전자)으로 삼고 이를 복제(참조)하여 새로운 객체를 생성합니다.
🔗 프로토타입 체인 (Prototype Chain)
특정 객체의 프로퍼티나 메서드에 접근할 때, 해당 객체에 그 속성이 없다면 부모 역할을 하는 프로토타입 객체(__proto__)를 따라 거슬러 올라가며 탐색합니다. 이를 프로토타입 체인이라고 합니다.
위 그림에서 배열 인스턴스인 myArray 자체에는 push() 메서드가 없지만, 내부 슬롯인 __proto__를 타고 부모격인 Array.prototype으로 올라가 해당 메서드를 찾아 실행하게 됩니다. 최상위 부모는 항상 Object.prototype입니다.
<!-- 프로토타입 기반 상속 예제 -->
<h4>🧬 생성자 함수와 프로토타입</h4>
<div id="output1" style="padding:15px; background:#1e293b; border-radius:8px; font-family:monospace; color:#cbd5e1; margin-bottom:20px; line-height: 1.6;"></div>
<h4>🚀 ES6 Class 문법 (Syntactic Sugar)</h4>
<div id="output2" style="padding:15px; background:#1e293b; border-radius:8px; font-family:monospace; color:#6ee7b7; line-height: 1.6;"></div>
<script>
function printLog(id, msg) {
document.getElementById(id).innerHTML += msg + '<br>';
}
/* ----------------------------------------------------
1. 고전적인 프로토타입(Prototype) 방식
----------------------------------------------------- */
// 생성자 함수
function Person(name) {
this.name = name;
}
// 프로토타입 객체에 공통 메서드 추가 (메모리 낭비 방지)
Person.prototype.sayHello = function() {
return '안녕하세요, 제 이름은 ' + this.name + '입니다.';
};
const kim = new Person('김코딩');
printLog('output1', 'kim.sayHello() 실행: ' + kim.sayHello());
// 객체 자체에는 sayHello가 없고 프로토타입 체인을 통해 찾음
printLog('output1', 'kim이 sayHello를 직접 가졌나요?: ' + kim.hasOwnProperty('sayHello'));
printLog('output1', 'kim의 __proto__ 가 부모의 prototype과 같나요?: ' + (kim.__proto__ === Person.prototype));
/* ----------------------------------------------------
2. ES6 Class 방식 (본질은 프로토타입과 동일함)
----------------------------------------------------- */
class Developer {
constructor(name) {
this.name = name;
}
// 이 메서드는 자동으로 Developer.prototype 에 저장됨
code() {
return this.name + '님이 코딩을 시작합니다 💻';
}
}
const park = new Developer('박자바');
printLog('output2', 'park.code() 실행: ' + park.code());
// 내부적으로 typeof Developer 는 'function' 임을 증명 (문법적 설탕)
printLog('output2', 'typeof Developer는 무엇일까요?: ' + (typeof Developer));
</script>