Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

이글이글

[2]React ES6 Classes 본문

react

[2]React ES6 Classes

suye0n6 2025. 3. 17. 13:56

Classes

ES6에서는 클래스가 도입되어있다.

 

클래스는 함수의 한 유형이지만, 키워드를 사용하여 function 초기화하는 대신 키워드를 사용하고 class 속성은 constructor() 메서드 내부에 할당한다.

 

class Car {
  constructor(name) {
    this.brand = name;
  }
}

 

클래스 네임은 대소문자를 주의해야한다.

 

class Car {
  constructor(name) {
    this.brand = name;
  }
}

const mycar = new Car("Ford");

 

생성자 함수는 객체가 초기화될 때 자동으로 호출된다.

 

클래스의 메서드

 

클래스의 사용자 정의 메서드를 추가할 수 있다.

 

class Car {
  constructor(name) {
    this.brand = name;
  }
  
  present() {
    return 'I have a ' + this.brand;
  }
}

const mycar = new Car("Ford");
mycar.present();

 

객체의 메서드 이름 뒤에 괄호를 붙여 매서드를 호출한다.

 


 

클래스 상속

 

클래스 상속을 만들려면 extends 키워드를 사용해야한다.

 

클래스 상속을 통해 생성된 클래스는 다른 클래스의 모든 메서드를 상속받는다.

class Car {
  constructor(name) {
    this.brand = name;
  }

  present() {
    return 'I have a ' + this.brand;
  }
}

class Model extends Car {
  constructor(name, mod) {
    super(name);
    this.model = mod;
  }  
  show() {
      return this.present() + ', it is a ' + this.model
  }
}
const mycar = new Model("Ford", "Mustang");
mycar.show();

 

해당 super() 메서드는 부모 클래스를 참조한다.

생성자 메서드에서 메서드를 호출하면 super() 부모의 생성자 메서드를 호출하고 부모의 속성과 메서드에 접근 가능하다.

 

'react' 카테고리의 다른 글

[6] React ES6 Spread Operator  (0) 2025.03.28
[5]React ES6 Destructuring  (0) 2025.03.28
[4] React ES6 Array Methods  (0) 2025.03.28
[3]ES6 Variables  (0) 2025.03.28
[1] REACT ES6  (0) 2025.03.17