본문 바로가기

컴퓨터공부/React

[React & Express] 03 class, constructor, static ,extend, super

by Life & study 2023. 5. 20.
반응형

https://codepen.io/pen/ (코드펜) 

 

class

 

React Class Components는 React에서 가장 오래된 방식 중 하나입니다. 이는 ES6 클래스 기반의 컴포넌트입니다. 

Class Components는 상태(State)과 라이프 사이클(Life cycle)을 관리하기 편하며, 클래스 내부에 메서드를 정의할 수도 있습니다. 또한, 이전 버전의 React에서 기본적으로 사용되던 방식 중 하나이므로, 여전히 많은 코드에서 사용됩니다.

React Class Components는 React.Component 클래스를 상속받아 생성됩니다. 이 클래스는 render() 메서드를 구현해야 한다.

 


// unnamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// 출력: "Rectangle"

// named
let Rectangle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
};
console.log(Rectangle.name);
// 출력: "Rectangle2"

에서

constructor는 무엇인가? 라이브러리인가?

'나의 정의 : constructor는 class 의 이름이다.'

 

constructor는 JavaScript의 클래스에서 사용되는 특별한 메서드입니다. 클래스를 인스턴스화할 때 호출되는 메서드로, 인스턴스의 초기화를 담당합니다. 이 메서드는 클래스에 필요한 모든 초기화 작업을 수행할 수 있습니다. 

먼저 첫 번째 예시에서는 이름이 없는 클래스를 생성하여 Rectangle에 할당하고, 이 클래스의 이름을 출력하는 코드입니다. 클래스는 객체 타입의 값으로, 함수와 마찬가지로 name 속성을 가지고 있습니다. 그래서 Rectangle.name은 "Rectangle"이라는 문자열을 출력합니다.

두 번째 예시에서는 클래스가 이름을 갖도록 정의하였습니다. Rectangle2라는 이름을 가지는 클래스를 생성하고, 동일한 이름을 클래스 선언 외부에서 참조할 수 있도록 let 키워드로 변수에 할당하였습니다. 이 예시에서도 constructor 메서드를 정의하여 클래스의 인스턴스 초기화 작업을 수행하고 있습니다.

 

인스턴스화 한다는것은?

나의 정의 : 'new 로 만든 속성을 가진 복제품이다'

 

인스턴스화(Instantiation)란, 클래스를 기반으로 객체를 생성하는 과정을 의미합니다. 클래스는 템플릿과 같은 역할을 합니다. 클래스를 정의한 후, 이를 바탕으로 실제 사용할 수 있는 객체를 만드는 것이 인스턴스화 과정입니다.
예를 들어, 클래스를 정의한 후 new 키워드와 함께 생성자 함수를 호출하여 인스턴스를 생성할 수 있습니다. 그리고 이렇게 생성된 인스턴스는 클래스에서 정의한 속성과 메서드를 모두 상속받게 됩니다.
예를 들어, 아래의 Rectangle 클래스를 기반으로 인스턴스를 생성해보면, 다음과 같은 코드로 작성할 수 있습니다.
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

const rectangle1 = new Rectangle(10, 20);
위 예시에서 rectangle1은 Rectangle 클래스의 인스턴스입니다. 즉, rectangle1 객체는 height와 width 속성을 가지고, Rectangle 클래스에서 정의한 메서드를 모두 사용할 수 있게 됩니다. 이렇게 인스턴스화를 하면, 클래스를 여러번 사용하여 동일한 형태의 객체를 계속해서 만들 수 있습니다.

 

static 메소드는 무엇인가?

나의 정의: '객체로 만들기 전에, 사용할수있는 메소드이다.'

 

static 메소드는 클래스에서 직접 호출 가능한 메소드입니다. 즉, static 메소드는 클래스 인스턴스의 속성과 메소드가 아니라, 클래스 자체의 속성과 메소드입니다.

static 메소드는 클래스의 인스턴스를 생성하지 않고도 바로 호출할 수 있어서, 유틸리티 클래스나 헬퍼 클래스 등에서 많이 사용됩니다. 대표적인 예로, Math 객체의 메소드들이 static 메소드입니다.

static 메소드를 정의할 때는, 함수 앞에 static 키워드를 붙여줍니다. static 메소드 내부에서는 this 키워드를 사용하여 클래스 자체의 속성이나 다른 static 메소드를 참조할 수 있습니다. 하지만, 인스턴스의 속성이나 메소드는 this를 사용하여 참조할 수 없습니다.

다음은 static 메소드를 정의하고 사용하는 예시입니다.

```
class Circle {
  constructor(radius) {
    this.radius = radius;
  }

  static computeArea(radius) {
    return 3.14 * radius * radius;
  }
}

const circle1 = new Circle(5);
const area = Circle.computeArea(5);  // static 메소드는 클래스의 인스턴스 없이 바로 호출합니다
```

위 예시에서 computeArea 메소드는 static 메소드로, 인스턴스를 생성하지 않고도 Circle 클래스에서 바로 호출할 수 있습니다. 이렇게 static 메소드는 클래스 인스턴스의 생성과는 무관하게 클래스 자체에서 바로 사용 가능한 유틸리티 메소드를 정의할 때 유용하게 사용할 수 있습니다.

 

extends 와 super의 관계는 무엇인가?

 

나의정의:

etxtend로 만든 객체는 , super로 불러와서 사용할수있다.

기존 클래스명 확장 확장할클래스이름 을 쓰고,

constructor (props)로 받고, 

    super(props); 로 받고,

this.state 를 상태변경을 = { name: "Child" }; 하면  ,  확장하는 클래스(extends)와 super로 클래스에 확장시켜서 값 전달가능하다, 

 

class Child extends Parent {
  constructor(props) {
    super(props);
    this.state = { name: "Child" };
  }

 

 

React에서 extends와 super는 JavaScript의 상속에 관한 문법을 활용한 것입니다. React에서 컴포넌트를 만들 때, React.Component를 상속 받아서 사용하는 형태로 작성합니다.

예를 들어, 다음과 같이 React 클래스를 상속해서 새로운 컴포넌트를 만들 수 있습니다.

```
import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}
```

위 예시에서 MyComponent 클래스는 React의 Component 클래스를 상속받고 있습니다.이를 통해 MyComponent 클래스는 React의 Component 클래스의 기능을 모두 사용할 수 있습니다.

또한, super() 메소드를 사용하여 부모 클래스인 Component의 생성자 함수를 호출할 수 있습니다. 이때, super() 메소드의 인자로 props 객체를 전달합니다. 이는 부모 클래스의 생성자가 props를 받는다면, 자식 클래스에서도 props를 사용할 수 있도록 하기 위함입니다.

```
import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'John Doe'
    };
  }

  render() {
    return (
      <div>
        <h1>Hello, {this.state.name}!</h1>
        <p>Welcome to my component.</p>
      </div>
    );
  }
}
```

위 예시에서 constructor() 메소드에서 super(props)를 호출하여 부모 클래스인 Component의 생성자를 실행하고, 이후에는 state 객체를 초기화해주고 있습니다. 이렇게 자식 클래스에서 super() 메소드를 호출함으로써 부모 클래스의 생성자를 호출하고, 부모 클래스에서 정의한 멤버 변수를 초기화할 수 있습니다.

 


2번째 예시,

 

React에서 extends와 super의 관계에 대해 설명해드리겠습니다.

React에서 클래스를 만들 때, extends를 사용하여 다른 클래스를 상속받을 수 있습니다. 이때, 상속받은 클래스의 생성자(constructor)를 호출하기 위해 super()를 사용합니다.

super()는 부모 클래스의 생성자를 호출하는 역할을 합니다. 이때, super()에 props를 전달하면 부모 클래스에서 props를 사용할 수 있습니다.

 

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "Parent" };
  }
}

class Child extends Parent {
  constructor(props) {
    super(props);
    this.state = { name: "Child" };
  }
}

위 코드에서 Child 클래스가 Parent 클래스를 상속받았습니다. Child 클래스의 생성자에서 super(props)를 호출하여 Parent 클래스의 생성자를 호출하고 있습니다.

 

3번째 예시,

 

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "Parent" };
  }
}

class Child extends Parent {
  constructor(props) {
    super(props);
    this.state = { name: "Child" };
  }

  render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
}

위 코드에서 Child 클래스가 Parent 클래스를 상속받았습니다. Child 클래스의 생성자에서 super(props)를 호출하여 Parent 클래스의 생성자를 호출하고 있습니다. 이때, Child 클래스에서 state를 재정의하고 있습니다.

위 코드를 실행하면 화면에 "Child"라는 텍스트가 출력됩니다.

반응형

댓글