반응형
prototype은 무엇인가.... 상속을 왜 받는가... 에 대한 고찰
일단 개념정리는 해놓자
예를 들어 Cat과 Dog라는 새로운 객체 생성자를 만든다고 가정해 보자.
그리고 해당 객체 생성자들에서 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으로 설정해 주었다.
반응형
'Javascript' 카테고리의 다른 글
[javascript] - 07 프로토타입과 클래스 - es6 클래스 예제 (0) | 2023.01.16 |
---|---|
[javascript] - 07 프로토타입과 클래스 - es6 class (0) | 2023.01.16 |
[javascript] 6. 배열 내장 함수 - test (0) | 2023.01.16 |
[javascript] 6. 배열 내장 함수 - reduce (0) | 2023.01.16 |
[javascript] 6. 배열 내장 함수 - filter (0) | 2023.01.16 |
댓글