home강의 홈으로
Section 13. 프로토타입
Lesson 2. 프로토타입과 상속

👉 MDN 문서 보기

function Bird (name, sound) { this.name = name; this.sound = sound; } Bird.prototype.fly = function () { console.log(`${this.name} ${this.sound} 비행중`); } function Eagle (name, sound, prey) { this.name = name; this.sound = sound; this.prey = prey; } Eagle.prototype.hunt = function () { console.log(`${this.name} ${this.prey} 사냥중`); } const bird = new Bird('새돌이', '파닥파닥'); const eagle = new Eagle('독돌이', '푸드덕', '토끼'); console.log(bird); console.log(eagle); bird.fly(); eagle.hunt();
  • 프로토타입 이름 (Object로 표시) 에 크게 신경쓰지 말 것
  • EagleBird로부터 상속받도록 만들려면?


I. 프로토타입으로 상속하기

Object.create 메서드

function Bird (name, sound) { this.name = name; this.sound = sound; } Bird.prototype.fly = function () { console.log(`${this.name} ${this.sound} 비행중`); } function Eagle (name, sound, prey) { this.name = name; this.sound = sound; this.prey = prey; } // ⚠️ 순서 주의! 상속을 먼저 받음 Eagle.prototype = Object.create(Bird.prototype); // Eagle.prototype = Bird.prototype; // 💡 비교해 볼 것 // 상속 이후 자신의 프로토타입 작성 Eagle.prototype.hunt = function () { console.log(`${this.name} ${this.prey} 사냥중`); } const bird = new Bird('새돌이', '파닥파닥'); const eagle = new Eagle('독돌이', '푸드덕', '토끼'); // 상속 구조 확인 console.log(bird); console.log(eagle); console.log( eagle instanceof Bird, bird instanceof Eagle ); bird.fly(); eagle.fly(); eagle.hunt();
  • 상속을 먼저 하고 자체 프로토타입 프로퍼티 입력
  • Object.create... 대신 Bird.prototype 대입 결과 비교 - eagle과 bird 모두 확인




II. 부모의 생성자 활용하기

  • 생성자에서 중복되는 부분 위임
  • class에서는 constructor에서 super 사용
function Bird (name, sound) { this.name = name; this.sound = sound; } Bird.prototype.fly = function () { console.log(`${this.name} ${this.sound} 비행중`); } function Eagle (name, sound, prey) { // 💡 call 호출방식 사용 Bird.call(this, name, sound); this.prey = prey } Eagle.prototype = Object.create(Bird.prototype); Eagle.prototype.hunt = function () { console.log(`${this.name} ${this.prey} 사냥중`); } const eagle = new Eagle('독돌이', '푸드덕', '토끼'); console.log(eagle); eagle.fly(); eagle.hunt();



III. 클래스로 구현

⭐ 클래스 역시 프로토타입을 기반으로 구현됨

클래스와 프로토타입

  • 클래스의 메서드는 프로토타입으로 들어가게 됨
  • extends - 프로토타입 상속도를 만듦
function AAA () { this.field = 1; this.run = function () { return 1; }; } class BBB { field = 1; run = function () { return 1; } } class CCC { field = 1; run () { return 1; } } console.log(new AAA()); // 인스턴스에 속함 console.log(new BBB()); // 인스턴스에 속함 console.log(new CCC()); // 프로토타입에 속함
  • run 함수 또는 메서드가 속한 곳 비교
  • 필드는 양쪽 모두 인스턴스에 속함


// ♻️ 새로고침 후 실행 class Bird { constructor (name, sound) { this.name = name; this.sound = sound; } fly () { console.log(`${this.name} ${this.sound} 비행중`); } } class Eagle extends Bird { constructor (name, sound, prey) { super(name, sound); this.prey = prey; } hunt () { console.log(`${this.name} ${this.prey} 사냥중`); } } const bird = new Bird('새돌이', '파닥파닥'); const eagle = new Eagle('독돌이', '푸드덕', '토끼'); console.log(bird); console.log(eagle); bird.fly(); eagle.fly(); eagle.hunt();


💡 인스턴스의 클래스/생성자함수 이름 출력

  • 무엇의 인스턴스인지 프로그램상에서 이름으로 파악할 때 유용
console.log( Object.getPrototypeOf(bird).constructor.name, Object.getPrototypeOf(eagle).constructor.name, Object.getPrototypeOf( Object.getPrototypeOf(eagle) ).constructor.name, );



IV. Mixin - Object.assign으로 조립하기

  • 상속 - 한 부모로부터만 물려받음
  • 믹스인 - 여럿을 조합하여 가져올 수 있음
const runner = { run : function () { console.log(`${this.name} 질주중`); } } const swimmer = { swim: function () { console.log(`${this.name} 수영중`); } } const flyer = { fly: function () { console.log(`${this.name} 비행중`); } } const hunter = { hunt: function () { console.log(`${this.name} 사냥중`); } } class Owl { constructor (name) { this.name = name; } } class FlyingFish { constructor (name) { this.name = name; } } class PolarBear { constructor (name) { this.name = name; } } Object.assign(Owl.prototype, flyer, hunter); Object.assign(FlyingFish.prototype, flyer, swimmer); Object.assign(PolarBear.prototype, runner, swimmer, hunter); const owl = new Owl('붱돌이'); const f_fish = new FlyingFish('날치기'); const p_bear = new PolarBear('극곰이'); console.log(owl); console.log(f_fish); console.log(p_bear); owl.fly(); owl.hunt(); f_fish.swim(); f_fish.fly(); p_bear.run(); p_bear.swim(); p_bear.hunt();

🤔얄코에게 질문하기질문은 반.드.시 이리로 보내주세요! ( 강의사이트 질문기능 ✖ )

강의에서 이해가 안 되거나 실습상 문제가 있는 부분,
설명이 잘못되었거나 미흡한 부분을 메일로 알려주세요!

답변드린 뒤 필요할 경우 본 페이지에
관련 내용을 추가/수정하도록 하겠습니다.

이메일 주소
yalco@yalco.kr
메일 제목 (반드시 아래 제목을 붙여넣어주세요!)
[질문] 제대로 파는 자바스크립트 (유료 파트) 13-2

🛑질문 전 필독!!

  • 구글링을 먼저 해 주세요. 들어오는 질문의 절반 이상은 구글에 검색해 보면 1분 이내로 답을 찾을 수 있는 내용들입니다.
  • 오류 메시지가 있을 경우 이를 구글에 복붙해서 검색해보면 대부분 짧은 시간 내 해결방법을 찾을 수 있습니다.
  • 강의 페이지에 추가사항 등 놓친 부분이 없는지 확인해주세요. 자주 들어오는 질문은 페이지에 추가사항으로 업데이트됩니다.
  • "유료파트의 강의페이지는 어디 있나요?" - 각 영상의 시작부분 검은 화면마다 해당 챕터의 강의페이지 링크가 있습니다.
  • 질문을 보내주실 때는 문제가 어떻게 발생했고 어떤 상황인지 등을 구체적으로 적어주세요. 스크린샷을 첨부해주시면 더욱 좋습니다.
🌏 Why not change the world?