• Feed
  • Explore
  • Ranking
/
/
    JavaScript

    [JavaScript]프로토타입

    JavaScripts 프로토타입, 상속
    studyTILTodayILearnd상속JavaScirpts프로토타입
    미
    미니
    2025.08.22
    ·
    5 min read

    - 프로토타입 (Prototype)

    1) Prototype Link, 2) Prototype Object 을 통틀어 프로토타입이라고 함

    • 프로토타입은 자바스크립트의 상속을 지원받기 위한 방법

    • 상속, 인스턴스

      • 객체 간 상속을 구현하기 위해 사용된다.

      • 부모의 역할을 하는 객체로서 다른 객체에 공유하고 프로퍼티, 메서드를 제공한다.

    • 자신의 상위 객체


    - 상속

    • 객체지향 프로그래밍의 가장 큰 장점

    • 어떤 객체의 프로퍼티 또는 메서드를 다른 객체가 상속받아 그대로 사용할 수 있는 것

    • 불필요한 중복을 제거한다.

    - 생성자 함수

    • new 연산자 + 첫 글자 대문자

    • 생성자 함수로 동일한 프로퍼티, 메서드 구조를 갖는 객체 여러개를 생성할 수 있다.

    function Family(role){
      this.role = role;
      this.introduce = () => {
        return `Hi. I'm $(role)! `
      }
    }
    
    const family1=new Role('mom');
    const family2=new Role('father');
    
    console.log(family1.introduce === family2.introduce);
    //false
    • family1, family2의 메서드인 introduce가 동일하지 않음

      • Family 생성자 함수는 인스턴스를 생성할 때 마다 introduce 메서드를 중복 생성 하기때문이다.

      • 모든 인스턴스가 메서드를 중복 소유한다.

    • 인스턴스를 생성할 떄마다 동일한 메서드를 생성한다.

      • 성능저하 + 불필요한 메모리 낭비

    function Family(role) {
      this.role = role;
    }
    
    Family.prototype.introduce = () => {
      return `Hi. I'm ${this.role}!`
    }
    
    const family1 = new Family('mom');
    const family2 = new Family('father');
    
    console.log(family1.introduce === family2.introduce); 
    // true
    • Family 생성자 함수의 prototype 프로퍼티로 프로토타입에 접근해 메서드 introduce 생성

    • Family 생성자 함수가 생성한 모든 인스턴스는 부모 객체 역할을 하는 프로토타입 Family.prototye -> introduce 메서드 상속


    - [[Prototype]] 접근 방법

    - __proto__ 접근자 프로퍼티

    • 모든 객체는 __proto__ 접근자 프로퍼티를 통해 [[Prototype]] 내부 슬롯에 접근할 수 있다.

    • 값을 획득(getter)하고 설정(setter) 하는 역할을 한다

      • get -> 현재 객체의 프로토타입 반환

      • set -> 객체의 프로토타입을 새 객체로 변경

    • 오래된 방식이라 최신 코드에선 잘 쓰이지 않는다.

      • 권장 : Object.getPrototypeOf / object.setPrototypeOf

    - Object.getPrototypeOf()

    • 객체의 [[Prototype]]을 안전하게 가져온다


    - 표준 메서드

    1) Object.getPrototypeOf(obj)

    • 객체의 [[Prototype]]을 안전하게 가져옴.

    const obj = {};
    console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
    

    2) Object.setPrototypeOf(obj, proto)

    • 객체의 [[Prototype]]을 변경.

    • 성능 이슈가 있으므로 잘 쓰지 않는 게 좋음.

    const parent = { y: 2 };
    const child = {};
    Object.setPrototypeOf(child, parent);
    console.log(child.y); // 2
    

    3) Object.create(proto)

    • 주어진 proto를 프로토타입으로 하는 새 객체를 생성.

    const parent = { z: 3 };
    const child = Object.create(parent);
    console.log(child.z); // 3
    

    - 프로토타입 체인

    • 위로 계속 거슬러 올라가면서 찾는 구조

      • 객체간 상속을 구현하는 방식

      • 어떤 객체도 Object.prototype을 가지게 된다.

    • 객체의 프로퍼티를 검색할 때,

      1. 자기 자신의 프로퍼티 확인

      2. 없으면 [[Prototype]]을 따라 상위 객체로 탐색

      3. 최종적으로 Object.prototype까지 올라감

      4. 그래도 없으면 undefined 반환

    const grandParent = { a: 1 };
    const parent = Object.create(grandParent);
    parent.b = 2;
    
    const child = Object.create(parent);
    child.c = 3;
    
    console.log(child.a); // 1 (grandParent에서 찾음)
    console.log(child.b); // 2 (parent에서 찾음)
    console.log(child.c); // 3 (자기 자신에서 찾음)
    console.log(child.toString); // Object.prototype에서 찾음
    

    - 프로토타입의 최상위 객체

    • 모든 객체의 끝에는 **Object.prototype**이 있음.

    • Object.prototype의 [[Prototype]]은 null. (즉, 더 이상 올라갈 수 없음)

    console.log(Object.getPrototypeOf(Object.prototype)); // null






    - 컬렉션 아티클