ES6부터 사용가능한 Class와 Super 키워드를 이용하여 강아지를 만들어보려고 한다.
Class 생성하기, Constructor
constructor는 생성자라고하는데, class에 생성된 객체를 생성하고 초기화하기 위한 특별한 메소드 이다. class에 하나씩만 가질 수 있으며, 두개이상의 constructor는 SyntaxError가 발생할 수 있다.
또한, class 안에서는 function 키워드를 사용하지 않는다.
class Dog{
constructor(name, color, eyecolor){
this.name = name;
this.color = color;
this.eyecolor = eyecolor;
}
sit(){
console.log(`${this.name}가 앉았습니다.`)
}
}
또리가 생성되었다. 상세히 보면, 또리는 Sit만 가능하다. 그런데 또리 말고도 뽀삐를 만들고 싶고, 뽀삐는 앉기말고도 손을 내미는법도 알았으면 좋겠다. 어떻게 만들면 좋을까?
Extends, Super
이때, extends와 super 키워드를 사용할 수 있다. extends 키워드를 이용하여 class 선언이나, 표현식에 대해 다른 자식(하위)class를 생성하기 위해 사용된다. 또, Super 키워드가 있는데, 해당 키워드는 부모(상위)classdml 함수를 호출 할때 사용한다.
class Hand extends Dog{
constructor(name, color, eyecolor){
super(name, color, eyecolor)
}
givehand(){
console.log(`${this.name}이 손처럼 보이는 발을 슬쩍 내밀었습니다.`)
}
}
proto 항목을 보면, 먼저 뽀삐는 Dog를 가지고 있다. 또리의 상위는 Object였다. 또, 뽀삐는 Dog class에 있던
sit 외에도 givehand를 가지고 있다.
뽀삐는 sit도 할수 있고, givehand도 가능하다!
'JavaScript' 카테고리의 다른 글
Web Architectures (0) | 2020.05.18 |
---|---|
[Data Structure]Linked List, Hash Table (0) | 2020.05.12 |
OOP(Object Oriented Programming) (0) | 2020.05.08 |
[Data Structure] Stack / Queue (0) | 2020.05.06 |
유효성 검사하기 중 getElementsByName 이 작동하지 않을 때 (0) | 2020.04.07 |