[React]리액트 학습 기록 - 클래스

gamja·2023년 1월 24일
0
post-thumbnail

클래스 생성 방법

 class Person {
 	name = 'Max';
	call = () => { ... }
 }

클래스 사용 방법

const myPerson = new person();	// 클래스 선언
myPerson.call();				// 함수 사용
console.log(myPerson.name);		// 변수 사용

클래스 상속 방법

class Person extends Master

👩‍💻실습

이전 자바스크립트

class Human{
  constructor(){
    this.gender = 'male';
  }
  printGender(){
    console.log(this.gender);
  }
}

class Person extends Human {
  constructor(){
    super();			// super()을 사용해 줌으로써 상속하고 있는 Human 클래스를 초기화해준다.
    this.name = 'Max';
    this.gender = 'female';
  }
  printMyName(){
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName();
person.printGender();
  • super() : 부모 생성자
  • super() Human 클래스의 기본 생성자를 통해서 gender가 male로 초기화가 되었지만, Person 클래스에서 gender를 female로 변경해줬다.

리액트에서 컴포넌트를 생성할 때 위와 같은 방식으로 사용되며, 이는 컴포넌트를 생성하는 두 가지 방식 중 하나이다.

ES6 차세대 자바스크립트

  • 생성자 함수를 따로 만들 필요가 없고, this를 사용하지 않아도 된다는 장점이 존재한다.
class Human {
  gender = 'male';

  printGender = () => {
    console.log(this.gender);
  }
}
class Person extends Human{
  name = 'Max';
  gender = 'female';
  
  printMyName(){
    console.log(this.name);
  }
}
const person = new Person();
person.printMyName();
person.printGender();

일반 자바스크립트를 ES6 자바스크립트로 변경해주면 위와 같다.

유데미 강의 참고
Maximilian Schwarzmüller - React 완벽 가이드 with Redux, Next.js, TypeScript

profile
눈도 1mm씩 쌓인다.

0개의 댓글