JavaScript Category/JavaScript

[JavaScript] 클래스

ReBugs 2024. 1. 18.

이 글은 혼자공부하는 자바스크립트(저자 : 윤인성)의 책 내용과 유튜브 동영상을 참고하여 개인적으로 정리하는 글임을 알립니다.


클래스 기본 형태

다른 프로그래밍 언어와 비슷한 형태이다.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <script>
      class Student {
        //생성자
        constructor (이름, 국어, 영어, 수학, 과학) {
          this.이름 = 이름
          this.국어 = 국어
          this.영어 = 영어
          this.수학 = 수학
          this.과학 = 과학
        }
		//메소드 -> 메소드는 콜백함수를 사용할 수 없음
        getSum () {
          return this.국어 + this.영어 + this.수학 + this.과학
        }
        getAverage () {
          return this.getSum() / 4
        }
        toString () {
          return `${this.이름}\t${this.getSum()}점\t${this.getAverage()}점\n`
        }
      }
      // 객체를 선언합니다.
      const students = []
      students.push(new Student('구름', 87, 98, 88, 90))
      students.push(new Student('별이', 92, 98, 96, 88))
      students.push(new Student('겨울', 76, 96, 94, 86))
      students.push(new Student('바다', 98, 52, 98, 92))

      //출력합니다.
      let output = '이름\t총점\t평균\n'
      for (const s of students) {
        output += s.toString()
      }
      console.log(output)
    </script>
  </head>
  <body>
  </body>
</html>

 

private

클래스 내부에서 사용되는 # 기호로 시작하는 이름으로 선언된 멤버가 private 멤버로 취급된다.

이러한 private 멤버는 클래스 외부에서 직접 접근할 수 없다.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <script>
      // 정사각형 클래스
      class Square {
        #length //private 변수

        constructor (length) {
          this.setLength(length)
        }

        setLength (value) { /*setter*/
          if (value <= 0) {
            throw '길이는  0보다 커야 합니다.'
          }
          this.#length = value
        }

        getLength (value) { /*getter*/
          return this.#length
        }
        
        //메소드
        getPerimeter () { return 4 * this.#length }
        getArea () { return this.#length * this.#length }
      }

      // 클래스 사용하기
      const square = new Square(10)
      console.log(`한 변의 길이는 ${square.getLength()}입니다.`)

      // 예외 발생시키기
      square.setLength(-10)
    </script>
  </head>
  <body>
  </body>
</html>

 

static

JavaScript에서 static 키워드는 클래스의 정적(static) 멤버를 정의할 때 사용된다.

정적 멤버는 클래스 자체에 속하며 인스턴스를 생성하지 않고도 클래스에서 직접 접근할 수 있는 멤버이다.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <script>
      class Square {
        #length
        static #conuter = 0 /*statc 키워드*/
        static get counter () { /*statc 메소드*/
          return Square.#conuter
        }
        constructor (length) { /*생성자*/
          this.length = length
          Square.#conuter += 1
        }

        static perimeterOf (length) {
          return length * 4
        }
        static areaOf (length) {
          return length * length
        }
        
        get length () { return this.#length }
        get perimeter () { return this.#length * 4 }
        get area () { return this.#length * this.#length }

        set length (length) {
          if (length < 10) {
            throw '길이는 0보다 커야 합니다.'
          }
          this.#length = length
        }
      }

      // static 속성 사용하기
      const squareA = new Square(10)
      const squareB = new Square(20)
      const squareC = new Square(30)
      console.log(`지금까지 생성된 Square 인스턴스는 ${Square.counter}개입니다.`)
      // static 메소드 사용하기
      console.log(`한 변의 길이가 20인 정사각형의 둘레는 ${Square.perimeterOf(20)}입니다.`)
      console.log(`한 변의 길이가 30인 정사각형의 둘레는 ${Square.areaOf(30)}입니다.`)
    </script>
  </head>
  <body>
  </body>
</html>

 

상속

JavaScript에서 클래스를 정의할 때, extends 키워드를 사용하여 다른 클래스를 상속할 수 있다.

만약 부모 클래스의 생성자(constructor)가 있는 경우, 하위 클래스(자식 클래스)에서는 super()를 호출하여 부모 클래스의 생성자를 명시적으로 호출해야 한다.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <script>
      // 사각형 클래스
      class Rectangle {
        constructor (width, height) {
          this.width = width
          this.height = height
        }

        // 사각형의 둘레를 구하는 메소드
        getPerimeter () {
          return 2 * (this.width + this.height)
        }

        // 사각형의 넓이를 구하는 메소드
        getArea () {
          return this.width * this.height
        }
      }

      // 정사각형 클래스
      class Square extends Rectangle {
        constructor (length) {
          super(length, length)
        }

      }

      // 클래스 사용하기
      const square = new Square(10, 20)
      console.log(`정사각형의 둘레: ${square.getPerimeter()}`)
      console.log(`정사각형의 넓이: ${square.getArea()}`)
    </script>
  </head>
  <body>
  </body>
</html>

'JavaScript Category > JavaScript' 카테고리의 다른 글

[JavaScript] 예외처리  (0) 2024.01.18
[JavaScript] 문서 객체 모델(DOM:Document Object Model)  (0) 2024.01.17
[JavaScript] 객체(Object)  (0) 2024.01.16
[JavaScript] 함수  (1) 2024.01.15
[JavaScript] 반복문  (0) 2024.01.14

댓글