[Javascript] Prototype Chain 설명

허션·2025년 9월 5일
0

공부

목록 보기
10/13

thumbnail
이미지 출처

javascript에서 모든 object는 (특정 class, 혹은 원래 존재하는 primitive type의 instance) 하나의 큰 상위 Object class의 prototype를 계승한다.
이때 Object class - parent class - child class 사이에서의 prototype에 대한 계승을 Prototype Chain이라 한다.

Prototype 정의 참고 :
[JavaScript] Class == Function & Prototype Inheritance

Inheritance와 prototype chain :

  class Parent {
    parentMethod() {
        // 
    }
  }

  class Child extends Parent {
      childMethod() {
          //
      }
  }

  const child = new Child();
  • Object.getPrototypeOf(child)
    -> 실행 결과 : Parent {}, Child class의 prototype는 Parent의 prototype를 '원형(=prototype)으로 한다.

  • Object.getPrototypeOf(Object.getPrototypeOf(child))
    -> 실행 결과 : {}, Parent class의 prototype는 기본적인 Object.prototype를 '원형'으로 한다.

  • Object.getPrototypeOf(Object.getPrototypeOf(Object.getPrototypeOf(child)))
    -> 실행 결과 : [Object: null prototype] {}, Object보다 상위의 class, 즉 Object.prototype보다 prototype chain에서 상위에 있는 것은 null 뿐이다.

    ➡️ 이런 꼬리물기와 같은 inheritance 관계가 바로 prototype chain이다.

Takeaway

이것 때문에 Child class에서 Parent class의 parentMethod()를 explicitly override하지 않고도 부를 수 있음. (child.parentMethod())
-> extends를 이용한 inheritance는 prototype의 모든 member function을 넘겨주는 식으로 작동하는 prototype inheritance라는 사실과도 연관이 있음.

  • 예시:
    class Welcome
        sayHello() {
        	return "Hello World!";
        }
    }
    const welcome = new Welcome();
    welcome.sayHello();
    위 코드에서 welcome 인스턴스는 class Welcome의 인스턴스이므로 Welcome.prototype에 있는 Welcome의 class method에 접근할 수 있는데, 이 class Welcome은 Object class를 계승하므로 인스턴스가Object.prototype에 있는 모든 것에 접근할 수 있다.
profile
다시해보자.

0개의 댓글