undefined
class - Constructor, extends 와 super 본문
반응형
1. class를 사용하는 이유?
- class를 사용하면 class 중괄호 속에서 일반 생성자 함수보다 더 쉽게 method 관리 가능
- class를 사용하지 않으면 일반 생성자 함수를 사용할 때 prototype안에 일일이 만든 method를 넣어줘야함
2. constructor는 무엇인가?
- class로 새로운 객체를 생성할 때마다 자동으로 실행된다.
3. extends는 무엇인가?
- 상위의 클래스를 지정함으로써 상위 클래스를 참조 받을 수 있다.
4. super는 무엇인가?
- 상위 클래스의 constructor요소를 자신의 constructor에서 참조할 수 있다.
- 하위 클래스 constructor안에서 this를 쓰기 위해선 super지정이 필수!
- extends와 함께 쓰인다.
5. 예시)
// Participant 아래에 Winner와 Loser class가 존재
class Participant {
constructor(name, age) {
name = this.name;
age = this.age;
}
//아래의 method는 Winner와 Loser에서 둘다 사용가능하다(extends활용)
isParticipant() {
console.log("I'm participant");
}
}
//Participant 참조
//super(name,age)를 통해 Participant의 constructor를 가져옴 => 아래의 this.grade 사용가능
class Winner extends Participant {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
isWinner() {
console.log("I'm Winner");
}
}
//Participant 참조
class Loser extends Participant {
isLoser() {
console.log("I'm Loser");
}
}
const jack = new Winner("Jack", 25, "A+");
const sherry = new Loser("Sherry", 21);
//배우고 기록하는 글입니다. 틀린 것이 있다면 알려주세요!
반응형
'Javascript' 카테고리의 다른 글
변수, 표현식과 문 - Day 02 (0) | 2022.09.27 |
---|---|
프로그래밍, 자바스크립트에 대하여 - Day 01 (0) | 2022.09.25 |
API 와 AJAX (0) | 2022.05.26 |
비동기식 함수 Promise/Async /Await (0) | 2022.05.25 |
for...of loop (0) | 2022.05.18 |
Comments