<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
class Square {
#length
constructor (length){
this.setLength(length)
}
setLength (value) {
if (value <=0) {
throw `the length over than 0`
}
this.#length = value
}
getLength (value){
return this.#length
}
getPerimeter () {return 4 * this.#length}
getArea () { return this.#length * this.#length}
}
const square = new Square(10)
console.log(`one length : ${square.getLength()}`)
square.setLength(-10)
</script>
</head>
<body>
</body>
</html>
### Class Definition: `Square`
- The `Square` class is designed to model a square with a specific length.
- It uses a private field `#length` to store the square's side length.
- The constructor takes an initial length for the square and sets it using the `setLength` method.
- The `setLength` method updates the length of the square if the new length is greater than 0; otherwise, it throws an error.
- The `getLength` method is defined but mistakenly accepts a `value` parameter that it doesn't use. This appears to be a minor oversight; the method is meant to return the current length of the square's side.
- `getPerimeter` and `getArea` methods calculate and return the square's perimeter and area, respectively, using the private `#length` field.
### Script Execution:
- An instance of `Square` is created with an initial length of 10.
- The length of one side of the square is logged to the console using `getLength()`, which should correctly display the length as there's no real use of the unintended `value` parameter in `getLength`.
- An attempt is made to set the square's length to -10 using `setLength(-10)`, which should throw an error due to the validation check in the `setLength` method, stopping execution at that point and logging the error message.
### Note on `getLength` Method:
- The method signature for `getLength` mistakenly includes a parameter `value` that it does not use. For clarity and correctness, the method should be defined as `getLength()` without parameters.
### Error Handling:
- When `square.setLength(-10)` is executed, the script will throw an error and log the message `the length over than 0` to the console. Note that the error message is somewhat unclear and could be revised for better clarity, perhaps to something like "Length must be greater than 0."
'개념 > 혼자 공부하는 Javascript' 카테고리의 다른 글
class) Ractangle class (0) | 2025.01.23 |
---|---|
method) forEach() (1) | 2025.01.22 |
method) JSON.parse() method (0) | 2025.01.20 |
method) JSON.stringify() method (0) | 2025.01.19 |
method) Lodash_sortBy() method (1) | 2025.01.18 |