Class 초기값 설정해주기
constructor(생성자)
constructor(생성자)를 이용하면 class 객체의 초기 값을 설정해 줄 수 있다.
단, class 내부에서 constructor는 한 개만 존재할 수 있다.
아래는 constructor를 이용하여 Person 클래스에 초기 값을 설정해 보았다.
class Person {
constructor() {
this.name = 'Sam'; //this 키워드로 프로퍼티 설정해주기
}
printName() { // 메서드
console.log(this.name); // 위의 this.name을 전달 받는다
}
}
const person = new Person(); // 위의 Person class를 const person에 지정한다.
person.printName(); // 결과: 'Sam'
Class를 상속하는 방법
아래와 같이 새로운 class Human을 만들어준 뒤 Person에서 extend 한 후 마지막에 person.printGender()을 하면 에러가 난다.
class Human { // 새로운 class
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
class Person extends Human { // Human class 추가
constructor() { // 생성자 함수
this.name = 'Sam'; //this 키워드로 프로퍼티 설정해주기
}
printName() { // 메서드
console.log(this.name); // 위의 this.name을 전달 받는다
}
}
const person = new Person(); // 위의 Person class를 const person에 지정한다.
person.printName(); // 결과: 'Sam'
person.printGender();
super() 메서드를 추가하라는 에러 메시지가 뜬다.
super
상위 클래스의 생성자 함수를 실행한다.
class Human { // 새로운 class
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
class Person extends Human {
constructor() {
super(); // 추가
this.name = 'Sam';
}
printName() { // 메서드
console.log(this.name);
}
}
const person = new Person();
person.printName();
person.printGender();
// 결과:
// "Sam"
// "male"
ES6
예전에는 constructor을 사용하였고 그렇기 때문에 this를 활용했어야 했다. 하지만 ES6가 나오면서 constructor을 명시할 필요가 없어졌고 그래서 super()을 사용하지 않아도 된다. 위의 코드를 ES6문법으로 쓴다면 아래와 같이 쓸 수 있다.
class Human {
gender = 'male';
printGender =() => {
console.log(this.gender);
}
}
class Person extends Human {
name = 'Sam'; //this 키워드로 프로퍼티 설정해주기
printName = () => { // 메서드
console.log(this.name); // 위의 this.name을 전달 받는다
}
}
const person = new Person(); // 위의 Person class를 const person에 지정한다.
person.printName();
person.printGender();
// 결과:
// "Sam"
// "male"
'프론트엔드 > JavaScript' 카테고리의 다른 글
[ javascript ] HTML, CSS, JS로 음악 플레이어 만들기 (4) | 2024.09.09 |
---|---|
[ Javascript ] Drop Down(드롭다운) 메뉴 만들기 (0) | 2024.04.23 |
[ JavaScript ] currentTarget vs target 차이점 (0) | 2022.11.17 |
[ JavaScript ] ES6의 화살표 함수 (0) | 2022.10.23 |
[ 자바스크립트 ] <script> 태그는 어디에 위치하는게 효율적일까? (0) | 2022.09.30 |
댓글