<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
class Square{
#length
constructor (length) {
this.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
}
}
const squareA = new Square(10)
console.log(`one side : ${squareA.length}`)
console.log(`perimeter : ${squareA.perimeter}`)
console.log(`area : ${squareA.area}`)
const squareB = new Square(-10)
</script>
</head>
<body>
</body>
</html>
### Overview of the `Square` Class
- **Private Field `#length`**: The `Square` class defines a private field `#length`, which is not directly accessible from outside the class. This encapsulation ensures that the length of the square can only be modified in controlled ways, specifically through the class's setter method.
- **Constructor**: The constructor takes an initial length for the square and assigns it using the setter method for `length`. This ensures that any square instance starts with a valid side length, as the setter includes validation.
- **Getter for `length`**: Allows reading the length of the square's side externally without directly accessing the private field.
- **Getter for `perimeter`**: Computes and returns the perimeter of the square (four times the length of one side).
- **Getter for `area`**: Computes and returns the area of the square (length of one side squared).
- **Setter for `length`**: Validates and sets the length of the square. It throws an error if an attempt is made to set the length to a non-positive value.
### Example Usage and Error Handling
- **`squareA` Instance**: An instance of `Square` is created with a side length of 10. The getters are used to log the side length, perimeter, and area to the console, demonstrating normal usage.
- **`squareB` Instance**: Attempts to create a `Square` instance with a negative side length, which triggers the error handling in the setter. Since the setter throws an error for non-positive lengths, this results in an exception being thrown and stops the script execution. To catch this error and handle it gracefully, a `try...catch` block would be needed around the instantiation.
### Key Takeaways
- **Encapsulation and Data Validation**: This example illustrates the power of encapsulation in object-oriented JavaScript, using private fields to protect class internals and ensuring data integrity through getter and setter methods.
- **Error Handling**: The use of conditional checks and error throwing in the setter method demonstrates a basic pattern for validating input data and preventing illegal states.
- **Implications of Uncaught Errors**: As the script stands, the attempt to create `squareB` with an invalid length will halt script execution due to the uncaught exception. In a real-world scenario, wrapping such operations in `try...catch` blocks allows for error handling that could, for instance, log a meaningful error message or revert to a default state.
### Correction for Real-world Use
To handle errors gracefully, instantiate `squareB` within a `try...catch` block:
```
try {
const squareB = new Square(-10);
} catch (error) {
console.error(error);
}
```
This approach prevents the script from halting and allows for meaningful error handling or recovery actions.
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
chapter 9) Static keyword (0) | 2024.12.29 |
---|---|
chapter 9) use to array (1) | 2024.12.28 |
chapter 8) Except (0) | 2024.12.26 |
chapter 8) print out exception (2) | 2024.12.25 |
chapter 8) try catch finally (0) | 2024.12.24 |