모든 객체는 생성될 때마다 프로토타입이 함께 자동으로 생성이 된다.
그 프로토타입을 통해서 상위 객체의 속성과 메서드를 찾아서 가져올 수 있다.
✔️ 프로토타입 체인을 사용해서 객체 지향 프로그래밍의 주요 개념 중 상속을 구현할 수 있다.
만약 아래와 같은 클래스 Human 이 있다고 하자. 그리고 new
키워드를 사용해서 thor 라는 인스턴스를 생성했다.
class Human { // --> 부모
constructor(name, age, gender) { // --> 자식에게 상속시킬 것들
this.name = name;
this.age = age;
this.gender = gender;
}
}
let thor = new Human('Thor', 40); // --> 자식
thor.name; // 'Thor'
thor.age; // 40
thor.eat(); // thor 에게 이런 메서드도 추가해줄 수 있다. 메서드가 어떤 코드를 실행하는지는 따로 정의해줘야 한다.
thor.sleep();
그런데 thor 를 생성하고나서 .name
, .age
와 같은 속성을 추가하지 않았는데도 thor.name
, thor.age
이 출력이 된다. 왜?
→ 부모 클래스의 prototype 에서 해당 속성을 가져왔기 때문이다. (상속)
만약 .name, .age 가 부모 클래스의 prototype 에 없었다면? → 그 부모의 부모 클래스 prototype 를 탐색한다.
이렇게 찾을 때 까지 계속 위로 올라가며 상위 부모 클래스의 prototype 를 탐색하게 되는데, 이 과정이 프로토타입 체인이다.
DOM도 부모/자식으로 이루어진 상속 관계이다.
브라우저에서 document.createElement(’div’)
로 만든 div
엘리먼트는, HTMLDivElement라는 클래스의 인스턴스이다.
__proto__
를 사용하면?let div = document.createElement('div');
div.__proto__ // HTMLDivElement
div.__proto__.__proto__ // HTMLElement
div.__proto__.__proto__.__proto__ // Element
div.__proto__.__proto__.__proto__.__proto__ // Node
div.__proto__.__proto__.__proto__.__proto__.__proto__ // EventTarget
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ // Object
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ // null
ECMAScript 2015 클래스 https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Classes_in_JavaScript#ecmascript_2015_%ED%81%B4%EB%9E%98%EC%8A%A4