본문 바로가기

React

class (컴포넌트 생성 방법1)

클래스는 class 키워드를 이용하여 정의하고, 프로퍼티와 메서드를 가질 수 있습니다.

 

메서드는 클래스에서 정의한 함수이며, 프로퍼티는 클래스에서 정의한 변수입니다.

 

class Person {
  constructor() {
    this.name = "LSH";
  }

  printMyName() {
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName(); // LSH 출력
console.log(person.name); // LSH 출력

클래스의 인스턴스를 생성할 때는 new 키워드를 사용하여 생성할 수 있습니다.

 

class Gender {
  constructor() {
    this.gender = "M";
  }

  printGender() {
    console.log(this.gender);
  }
}

class Person extends Gender {
  constructor() {
    super();
    this.name = "LSH";
  }

  printMyName() {
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName(); // LSH 출력
person.printGender(); // M 출력

또한 클래스는 상속을 받을 수 있는데 extends 키워드 뒤에 상속받을 클래스를 작성해주시면 됩니다.

 

이렇게 상속을 받는다는 것은 다른 클래스에 있는 프로퍼티와 메서드를 잠재적으로 새로운 프로퍼티와 메서드에 추가한다는 의미가 됩니다.

 

서브 클래스에서는 super 생성자를 먼저 호출해주어야 합니다.

 

만약 다른 클래스를 확장하고 생성자를 실행한다면 필요 없지만, 그렇지 않다면 생성자 함수 안에 super() 메서드를 추가해주어야 합니다.

 

서브 클래스 안에 super() 메서드를 추가해주게 되면 상위 클래스의 생성자 함수가 실행되게 됩니다.

 

 

class Gender {
  constructor() {
    this.gender = "M";
  }

  printGender() {
    console.log(this.gender);
  }
}

class Person extends Gender {
  constructor() {
    super();
    this.name = "LSH";
    this.gender = "F";
  }

  printMyName() {
    console.log(this.name);
  }
}

const person = new Person();
person.printMyName(); // LSH 출력
person.printGender(); // F 출력

이렇게 서브 클래스, 즉 상속받은 클래스에서 gender을 다시 할당해주게 되면 person.printGender()의 출력 값도 변경되게 됩니다.

 

 

 

(컴포넌트 생성 방법1) class는 react에서 컴포넌트를 생성할 때 사용됩니다.