09-2. 프로토타입과 클래스 - 생성자 상속하기

function Dog(name, sound) {
    this.type = '개';
    this.name = name;
    this.sound = sound;
}

function Cat(name, sound) {
    this.type = '고양이';
    this.name = name;
    this.sound = sound;
}

Dog.prototype.say = function(){  //이 함수를 2번이나 작성하는 불필요한 코
    console.log(this.sound)
}

Cat.prototype.say = function(){  //이 함수를 2번이나 작성하는 불필요한 코드
    console.log(this.sound)
}

const dog = new Dog('멍멍이', '멍멍');
const car = new Cat('야옹이', '야옹');

코드 중복을 없에기 위한 상속방법

function Animal(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
}

Animal.prototype.say = function(){ 
    console.log(this.sound)
}

function Dog(name, sound) {
    Animal.call(this, '개', name, sound);
}

function Cat(name, sound) {
    Animal.call(this, '고양이', name, sound);
}

Dog.prototype = Animal.prototype;
Cat.prototype = Animal.prototype;


const dog = new Dog('멍멍이', '멍멍');
const car = new Cat('야옹이', '야옹');

dog.say();
car.say();
// 결과)
멍멍

Last updated