온라인 강의/React 완벽 가이드 [Udemy]
15. 클래스 이해하기
유호야
2023. 5. 31. 07:12
반응형
클래스는 객체를 위한 핵심 청사진 같은 것이다
클래스 내부의 프로퍼티와 함수
클래스는 생성자 함수를 만드는 더 편한 방법이다. 그래서 클래스를 가지고 자바스크립트 객체를 생성할 수 있다.
또 클래스에서는 '상속'을 사용할 수 있다.
class Person {
}
클래스를 만들면 그 내부에서 프로퍼티를 사용할 수 있고 가장 간단한 형태의 프로퍼티는 생성자 함수를 추가하는 것이다. 클래스의 객체를 생성할 때마다 실행할 것입니다.
메서드는 메서드의 이름 다음에 중괄호를 넣어서 만들 수 있다
그리고 this 키워드로 property를 설정할 수 있는데
class Person {
constructor() {
this.name = 'Max';
}
printMyName() {
console.log(this.name);
}
}
const person = new Person();
person.printMyName();
// 출력
// Max
class Human {
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
extends 기능
extends를 통해서 다른 클래스에 있는 기능을 사용할 수 있다
class Human {
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
class Person extends Human {
constructor() {
this.name = 'Max';
}
printMyName() {
console.log(this.name);
}
}
위와 같이 사용하면 에러가 발생한다
왜?
서브클래스에서 super 생성자를 먼저 호출해야 하기 때문이다
class Human {
constructor() {
this.gender = 'male';
}
printGender() {
console.log(this.gender);
}
}
class Person extends Human {
constructor() {
super();
this.gender = 'female';
this.name = 'Max';
}
printMyName() {
console.log(this.name);
}
}
Person 클래스 내부의
super();
this. Gender = 'female';
위 함수들처럼
super() 를 작성하고
부모 클래스의 property 들도 변경 가능하게 된다
=> 확장 되었기 때문에
리액트에서 클래스는 컴포넌트를 생성할 때 사용된다.그리고 이것은 컴포넌트를 생성하는 두 방법 중의 하나이다.클래스는 생성자 함수와 비슷하고 클래스는 자바스크립트 객체를 사용하기 위한 청사진 같은 것이다.
또한 상속은 '프로토타입'과 비슷하다
반응형