본문 바로가기
개념/혼자 공부하는 Javascript

chapter 9) Static keyword

by kiseno 2024. 12. 29.
728x90
반응형
SMALL
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        class Square {
            #length
            static #counter = 0
            static get counter () {
                return Square.#counter
            }

            constructor (length) {
                this.length = length
                Square.#counter += 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 <= 0) {
                    throw `over than 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(`one side length 20 perimether ${Square.perimeterOf(20)}`)
        console.log(`one side length 30 Area ${Square.areaOf(30)}`)
    </script>
</head>
<body>

</body>
</html>

### Key Concepts Illustrated

- **Private Field `#length`**: Utilizes a private field to encapsulate the side length of a square, preventing direct access from outside the class.

- **Static Property `#counter`**: A private static property tracks the total number of `Square` instances created. This is a private field and is accessed through a public static getter.

- **Static Getter for `counter`**: Allows external access to the `#counter` property to see how many instances of the `Square` class have been created, without permitting modification.

- **Constructor**: Initializes new instances with a given length while ensuring the length is positive and increments the `Square` instance counter.

- **Static Methods `perimeterOf` and `areaOf`**: These methods allow calculating the perimeter and area of a square given a side length, without needing to create a `Square` instance. This demonstrates the utility of static methods for operations that are relevant to the class as a whole rather than to individual instances.

- **Instance Getters for `length`, `perimeter`, and `area`**: These provide access to an instance's length, calculate its perimeter, and calculate its area, showcasing encapsulation and the use of getters for derived properties.

- **Setter for `length`**: Validates and sets the side length of a square, enforcing a positive length.

### Example Usage

- **Creating Instances**: Creates three instances of `Square` with different lengths (10, 20, 30). Each creation increments the static `#counter` to track the total number of instances.

- **Accessing Static Property**: Outputs the total number of `Square` instances created using `Square.counter`.

- **Using Static Methods**: Demonstrates how to use static methods to calculate the perimeter of a square with a side length of 20 and the area of a square with a side length of 30, without creating `Square` instances.

### Output

- **Total Instances**: Logs the total number of created `Square` instances to the console, showing "지금까지 생성된 Square 인스턴스는 3개 입니다" (which translates to "The total number of Square instances created so far is 3").
  
- **Static Method Calculations**: Logs the results of static calculations for perimeter and area, demonstrating that these properties can be obtained without an actual `Square` object.

### Practical Implications

This example elegantly demonstrates how classes in JavaScript can be designed to encapsulate data and behavior, use static properties and methods for class-wide operations, and manage instance creation tracking. It provides a solid foundation for understanding how encapsulation, static properties, and methods work together in object-oriented JavaScript.

728x90
반응형
LIST