자바스크립트의 클래스

여민수·2022년 9월 19일
0
post-thumbnail

ES2015 클래스 구문


클래스란?

  • 사전에 정의된 속성 및 메소드를 이용해 객체를 생성하기 위한 blueprint
  • 자바스크립트는 실제로 클래스를 지원하지는 않음
    • 다만, 자바스크립트에 이미 존재하는 프로토타입 기반 상속자들을 구문적으로 눈속임하여 클래스처럼 보이게 만듦

클래스 선언 방법

  class Student{
    constructor(firstName, lastName){
      this.firstName = firstName;
      this.lastName = lastName;
    }
  }
  • 새로운 인스턴스 객체를 초기화 할 때는 constructor를 사용해 원하는 인스턴스를 생성, 초기화 수 있음
  • 객체를 인스턴스화하기 위해선 new 키워드를 사용
      let firstStudent = new Student("Colt", "Steele");
      let secondStudent = new Student("Blue", "Steele");
    • firstStudent는 student 클래스의 인스턴스, firstStudent의 성은 Colt, 이름은 Steele이 됨

instance 메소드

class Student{
  constructor(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
  }
  fullName(){
    return `Your full name is ${this.firstName} ${this.lastName}`;
  }
}

let firstStudent = new Student("Colt", "Steele");
firstStudent.fullName(); // "Colt Steele"
  • 인스턴스 메소드란 클래스에 새롭게 만들어진 인스턴스가 자유롭게 사용할 수 있는 클래스 내의 메소드를 의미
    • 위 예제에서는 fullName()이 인스턴스 메소드에 해당

class 메소드

  • static 키워드
    • static은 클래스 내 정적 메소드를 의미
    • 정적 메소드는 클래스의 인스턴스 없이 호출이 가능하며, 클래스가 인스턴스화 되면 호출할 수 없음
    • 정적 메서드는 종종 애플리케이션의 유틸리티 함수를 만드는데 사용
    • ex)
      class Student{
        constructor(firstName, lastName){
        this.firstName = firstName;
        this.lastName = lastName;
        }
        fullName(){
          return `Your full name is ${this.firstName} ${this.lastName}`;
        }
        static EnrollStudents(){
          return "ENROLLING STUDENTS";
        }
      } 
      let firstStudent = new Student("Colt", "Steele");
      firstStudent.EnrollStudents(); // error
      Student.EnrollStudents(); // "ENROLLING STUDENTS"
      	
      • 즉, static 키워드를 사용한 클래스 메소드는 개별 인스턴스와는 무관한 기능
  • 클래스에서의 this
    • 클래스 내에서 this는 클래스로부터 생성된 객체, 즉 실제 인스턴스를 참조
profile
FE develop을 하고 싶은 대학생

0개의 댓글