-
Section 13. 자바스크립트 프로토타입과 상속자바스크립트 2023. 4. 8. 17:13
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); //Bird {name: '새돌이', sound: '파닥파닥'} console.log(eagle); //Eagle {name: '독돌이', sound: '푸드덕', prey: '토끼'}
bird.fly(); //새돌이 파닥파닥 비행중 eagle.hunt(); //독돌이 토끼 사냥중
프로토타입 이름에는 크게 신경쓰지 않아도 된다. Object로 표시됐다.
여기서 Eagle이 Bird로부터 상속받게 만드려면??
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);
Eagle이 프로토타입을 통해 Brid를 상속받은 것을 확인할 수 있다.
console.log( eagle instanceof Bird, bird instanceof Eagle ); // true false
bird.fly(); //새돌이 파닥파닥 비행중 eagle.fly(); //독돌이 푸드덕 비행중 eagle.hunt(); //독돌이 토끼 사냥중
주의해야 할 점은 상속을 먼저 하고 프로퍼티를 입력해야 한다는 것이다.
II. 부모의 생성자 활용하기
생성자에서 중복되는 부분을 위임한다.
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);
call 호출방식을 사용하여 중복되는 부분을 부모 생성자에게 위임했다.
eagle.fly(); //독돌이 푸드덕 비행중 eagle.hunt(); //독돌이 토끼 사냥중
class에서는 생성자에서 super를 사용하는 점을 기억하자
인스턴스의 클래스 / 생성자 함수 이름을 출력하는 방법
console.log( Object.getPrototypeOf(bird).constructor.name, Object.getPrototypeOf(eagle).constructor.name, Object.getPrototypeOf( Object.getPrototypeOf(eagle) ).constructor.name, ); /Bird Bird Bird
무엇이 인스턴스인지 프로그램상에서 이름으로 파악할 때 유용하다.
III. 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);
.assign으로 여럿을 조합하여 조립한 것을 볼 수 있다.
owl.fly(); //붱돌이 비행중 owl.hunt(); //붱돌이 사냥중 f_fish.swim(); //날치기 수영중 f_fish.fly(); //날치기 비행중 p_bear.run(); //극곰이 질주중 p_bear.swim(); //극곰이 수영중 p_bear.hunt(); //극곰이 사냥중
'자바스크립트' 카테고리의 다른 글
Section 14. 자바스크립트 프로미스 (0) 2023.04.10 Section 14. 자바스크립트 비동기의 개념과 타임아웃 (0) 2023.04.08 Section 13. 자바스크립트 프로토타입의 개념 (0) 2023.04.08 Section 12. 자바스크립트 this의 정적 바인딩 (0) 2023.04.07 Section 12. 자바스크립트 this의 동적 바인딩 (0) 2023.04.07