[javascript] - 07 프로토타입과 클래스 - 객체 생성자 상속받기

HongDuHyeon·2022년 2월 9일
0
post-thumbnail
prototype은 무엇인가.... 상속을 왜 받는가... 에 대한 고찰
일단 개념정리는 해놓자

예를 들어 CatDog라는 새로운 객체 생성자를 만든다고 가정해보자.
그리고 해당 객체 생성자들에서 Animal의 기능을 재사용하려면 아래 코드처럼 할 수 있다.

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

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

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

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

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

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

새로만든 Dog()과 Cat()에서 Animall.call을 해주고 있다.
첫번째 인자에는 this를 넣어줘야하고 그 이후에는 객체 생성자 함수에서 필요로 하는 파라미터를 넣어줘야한다.

그리고 prototype을 공유해야 하기 때문에 상속받은 객체 생성자를 만들고 prototype값을 Animal.prototype으로 설정해주었다.

profile
마음이 시키는 프론트엔드.. RN과 IOS를 곁들인..

0개의 댓글

관련 채용 정보