Javascript/프로토타입 & 클래스

객체 생성자 상속하기 Prototype

appmaster 2021. 2. 1. 12:54
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 cat = new Cat('야옹이', '야옹');

// dog.sharedValue;
// cat.sharedValue;

dog.say();
cat.say();

Dog함수에서 매개변수로 type은 자체적으로 넣을것이기 때문에 필요하지않습니다.

call이라는 함수를 호출할때는 첫번째 파라미터에는 Dog객체 함수에서 this를 넣어주고 그 다음으로 들어오는 '개', name, sound는 Animal 함수에서 가져오는겁니다.

 

 

즉, prototype은 공유되는 값을 설정하는것이고 객체 생성자는 new라는 키워드를 사용해서 호출을 했을때 새로운 객체를 만들게 됩니다.