-
프로토타입 체인 (extends, super)FRONTEND/Javascript 2022. 7. 24. 23:01
https://www.youtube.com/watch?v=_DLhUBWsRtw&t=1256s
프로토타입 체인이란?
프로토타입 객체가 상위 프로토타입 객체로부터 메소드와 속성을 상속받을 수 있다는 것입니다.
상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있습니다.
✓ 프로토타입 체인이 동작하는 방식
해당 instance가 내가 찾는 property나 method를 가지고 있지 않다면
→ 상위 prototype을 참고하고 거기에 찾던 게 있으면 그 값을 가져온다.
→ 없는 경우 한 세대 더 올라가서 prototype을 참고하고 있으면 거기서 가져오고 아니면.. 반복
extends
기본 클래스(상위 클래스)의 property에 덧붙여 파생 클래스의 property와 method를 설정할 수 있게 해줍니다.
super
상위 클래스의 property와 method를 사용할 수 있게 해줍니다.
class Shape { constructor(width,height,color) { this.width = width; this.height = height; this.color = color; } draw() { console.log (`drawing ${this.color} color!`) } getArea () { return this.width * this.height; } } class Rectangle extends Shape {} // Rectangle은 Shape의 property와 method를 상속받는다 class Triangle extends Shape { // Triangle은 Shape의 property와 method를 상속받는다 draw() { super.draw(); // Triangle의 draw 메서드 실행 console.log('▲') } getArea() { return this.width * this.height / 2; } } const rectangle = new Rectangle (20,20,'blue'); rectangle.draw(); const triangle = new Triangle (20,20,'red'); triangle.draw();
이 때, 상위 클래스의 전체 속성을 상속받을 수 있으며 특정한 몇몇 속성만 상속 받는 것도 가능합니다.
class Person { constructor(first, last, age, gender, interests) { this.name = { first, last }; this.age = age; this.gender = gender; this.interests = interests; } // Person 생성 class Teacher extends Person { //Person의 속성을 상속받을 건데 constructor(first, last, age, gender, interests, subject, grade) { super(first, last, age, gender, interests); // first, last, age, gender, interests는 Person의 property를 상속받고 this.subject = subject; this.grade = grade; // subject, grade는 상속받지 않을 것 } }
'FRONTEND > Javascript' 카테고리의 다른 글
자꾸 헷갈려서 빡쳐서 쓰는 글 (splice, split, slice) (0) 2022.07.28 getter와 setter, get과 set 키워드 [작성중] (0) 2022.07.25 프로토타입과 클래스 (prototype,__proto__) (0) 2022.07.24 객체 지향 프로그래밍 (OOP) 주요 개념 4가지 (캡슐화, 추상화, 상속, 다형성) (0) 2022.07.24 객체 지향 프로그래밍 (new, this, class, instance) (0) 2022.07.24