JavaScript 프로토타입 체인과 객체 지향 메커니즘

인스턴스 멤버와 클래스 멤버의 구분

인스턴스 멤버

인스턴스 멤버는 생성자 함수 내부에서 this를 통해 정의되는 속성과 메서드를 의미합니다. 이들은 객체가 인스턴스화 때마다 개별적으로 생성되며, 반드시 생성된 객체를 통해서만 접근할 수 있습니다.

function Musician(name, debutYear) {
    this.name = name;
    this.debutYear = debutYear;
    this.perform = function() {
        console.log('무대를 시작합니다');
    };
}

const artist = new Musician('박효신', 2000);
console.log(artist.name);  // 인스턴스를 통한 접근
artist.perform();

정적 멤버

정적 멤버는 생성자 함수 자체에 직접 부여되는 속성으로, 모든 인스턴스가 공유하며 생성자 함수를 통해서만 접근 가능합니다.

function Musician(name, debutYear) {
    this.name = name;
    this.debutYear = debutYear;
}

Musician.agency = 'YG Entertainment';  // 정적 속성 추가

const artist = new Musician('태양', 2006);
console.log(Musician.agency);  // 생성자를 통한 접근
console.log(artist.agency);    // undefined - 인스턴스로는 접근 불가

생성자 함수의 메모리 효율성 문제

생성자 함수 내부에 메서드를 직접 정의하면, 매 인스턴스마다 동일한 기능의 함수 객체가 중복 생성되어 메모리가 낭비됩니다.

프로토타입을 활용한 메서드 공유

JavaScript의 모든 생성자 함수는 prototype 속성을 보유합니다. 이 프로토타입 객체에 정의된 메서드는 해당 생성자로 생성된 모든 인스턴스가 공유하여 사용합니다.

function Musician(name, debutYear) {
    this.name = name;
    this.debutYear = debutYear;
}

Musician.prototype.perform = function() {
    console.log(this.name + '님이 공연을 시작합니다');
};

const singer1 = new Musician('아이유', 2008);
const singer2 = new Musician('성시경', 2002);

singer1.perform();  // "아이유님이 공연을 시작합니다"
singer2.perform();  // "성시경님이 공연을 시작합니다"

내부 프로토타입 링크

모든 객체는 [[Prototype]]이라는 내부 슬롯을 가지며, 이는 생성자의 prototype 객체를 참조합니다. 브라우저 환경에서는 __proto__를 통해 이 연결을 확인할 수 있으나, 표준화된 접근 방법은 Object.getPrototypeOf()를 사용하는 것이 권장됩니다.

constructor 속성의 역할

프로토타입 객체는 constructor 속성을 통해 자신을 생성한 함수를 역참조합니다. 프로토타입을 객체 리터럴로 재정의할 경우 이 연결이 끊어지므로, 명시적으로 복원해야 합니다.

function Musician(name, genre) {
    this.name = name;
    this.genre = genre;
}

Musician.prototype = {
    constructor: Musician,  // 생성자 연결 복원
    play: function() {
        console.log('음악을 재생합니다');
    },
    compose: function() {
        console.log('작곡을 시작합니다');
    }
};

const composer = new Musician('윤상', '발라드');
console.log(composer.constructor === Musician);  // true

프로토타입 체인의 동작 원리

객체의 속성 접근 시 JavaScript는 다음 순서로 검색을 수행합니다:

  1. 객체 자신의 속성 확인
  2. 내부 프로토타입 링크를 따라 상위 프로토타입 검색
  3. Object.prototype까지 도달 후 종료
  4. 찾지 못하면 undefined 반환

이 연결 고리를 프로토타입 체인이라 부르며, 속성 상속과 메서드 공유의 핵심 메커니즘입니다.

삼각형 관계 정리

  • 생성자.prototype → 프로토타입 객체
  • 인스턴스.__proto__ → 동일한 프로토타입 객체
  • 프로토타입.constructor → 생성자 함수

this 바인딩 규칙

생성자 함수와 프로토타입 메서드 내부의 this는 모두 해당 메서드를 호출한 인스턴스를 가리킵니다.

function Musician(name) {
    this.name = name;
    this.introduce = function() {
        console.log('저는 ' + this.name + '입니다');
    };
}

Musician.prototype.greet = function() {
    console.log('안녕하세요, ' + this.name + '입니다');
};

const performer = new Musician('김범수');
performer.introduce();  // 생성자 내부의 this
performer.greet();      // 프로토타입 메서드의 this

태그: JavaScript Prototype Constructor Object-Oriented Inheritance

6월 13일 19:55에 게시됨