티스토리 뷰

class(클래스)?

: 객체를 만들기 위한 프로퍼티와 메서드가 명시된 청사진 

  • 이 청사진에 기반한 객체들을 인스턴스화할 수 있다.
  • 엄밀히 말하자면 JS는 실제로 클래스를 지원하지 않는다.(JS에 이미 존재하는 프로토타입 기반 상속자들을 구문적으로 눈속임한 syntatical sugar이다.) -> 진정한 OOP는 지원하지 않음
  • 프로토타입 기반 상속자 혹은 프로토타이핑으로 불리는 무엇인가를 이용하는 것 
  • new 키워드를 통해 생성되거나 인스턴스화 된다.
  • 생성자 함수는 클래스가 인스턴스화 할 때 동작하는 특별한 함수이다.

클래스를 왜 배워야할까🤔? 

앞으로 수 많은 자료 구조들을 클래스(ES2015최신 문법)로 구현할 것이기 때문이다. 

1. class syntax (문법)

class Student {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
}
  • class명은 카멜케이스를 사용한다.(대문자 시작)
  • constructor()는 새로운 스튜던트 인스턴스를 인스턴스화시킬 때 사용되는 특별한 메서드이다.

1-1. 클래스를 통해 새로운 인스턴스 생성하기

:클래스로부터 새로운 객체를 인스턴스화하는 방식 => new 키워드 사용

let firstStudent = new Student('gamza', 'kim');
let secondStudent = new Student('alex', 'chang');
  • 각각은 기본적으로 위의 청사진(클래스) 패턴에 기반하는 새로운 Student 객체를 생성하게 된다.
class Student {
  constructor(firstName, lastName, year) {
    //this를 생성자 함수 내부에서 사용허게 되면, 개발 클래스 인스턴스 즉 개별 Student 인스턴스를 지칭하게 됩니다.
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = year;
  }
}
let firstStudent = new Student('gamza', 'kim');
let secondStudent = new Student('alex', 'chang');
secondStudent.grade = 4;
console.log(secondStudent.grade); //4

2. Instance methods(인스턴스 메서드)

: 클래스 단위에서 동작하는 것이 아니라 개별 인스턴스에 관련된 메서드

class Student {
  constructor(firstName, lastName, year) {
    //this를 생성자 함수 내부에서 사용허게 되면, 개발 클래스 인스턴스 즉 개별 Student 인스턴스를 지칭하게 됩니다.
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = year;
    this.tardies = 0;
    this.scores = [];
  }
  fullName() {
    return `your full name is ${this.firstName} ${this.lastName};`;
  }
  markLate() {
    this.tardies += 1;
    if (this.tardies >= 3) {
      return 'you are expelled';
    }
    return `${this.firstName} ${this.lastName} has been late ${this.tardies} times`;
  }
  addScores(score) {
    this.scores.push(score);
    return this.scores;
  }
  calculateAverage() {
    if (this.scores.length === 0) {
      return "there's no scores";
    }
    let sum = this.scores.reduce((acc, crr) => acc + crr);
    return Math.floor(sum / this.scores.length);
  }
}
let firstStudent = new Student('gamza', 'kim', 1);
let secondStudent = new Student('alex', 'chang', 2);
console.log(firstStudent.markLate()); //gamza kim has been late 1 times
console.log(firstStudent.markLate());
console.log(firstStudent.markLate()); //you are expelled
firstStudent.addScores(83);
firstStudent.addScores(55);
console.log(firstStudent.calculateAverage()); //69

2-1. Class Methods(클래스 메서드)

클래스 메서드 = static 메서드 

📌 "static" 키워드와 static method ? 
  • 이 static 키워드는 클래스에 종속되는 반면 클래스의 개별 인스턴스 메서드에는 반드시 종속적일 필요가 없는 메서드 혹은 기능들을 생성하도록 해준다.
  • 거의 사용하진 않는다. 
  • ⭐ static 키워드는 스태틱 메서드를 만들어주며 스태틱 메서드는 클래스의 인스턴스화 없이도 호출될 수 있으며 클래스 인스턴스를 통해서는 호출될 수 없다. -> 어플리케이션을 위한 유틸리티 기능을 생성하기 위해 자주 사용된다.
  • 즉, static 메서드는 특정 인스턴스와는 무관하며 일반적인 종합 기능 혹은 유틸리티 펑션 등과 같이 그냥 필요한 클래스의 한 부분이라고 할 수 있다.
// *static method(class method)
{
  class Point {
    constructor(x, y) {
      this.x = x;
      this.y = y;
    }
    static distance(a, b) {
      //? 두 점 사이의 거리를 계산하는 거리 공식 사용
      const dx = a.x - b.x;
      const dy = a.y - b.y;
      return Math.hypot(dx, dy);
    }
  }
  const p1 = new Point(5, 5);
  const p2 = new Point(10, 10);
  console.log('p1', p1);
  console.log('p2', p2);
  console.log(Point.distance(p1, p2)); //7.0710678118654755
}
댓글