
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
무한루프가 되는 이유가 set 함수 내에서 할당하기 위해 다시 set을 돌기 때문이라고 하셨습니다.
class 내부의 이름을 전부 this._height로 바꾼 뒤 set을 했을 때에는 왜 set의 루프에 갇히지 않는지 궁금합니다.
구글링 했을 때는 다음과 같이 이해했는데 맞게 이해했는지 궁금합니다.
class 내부에서 get의 결과로 가상의 프로퍼티(속성)이 생기는데, get width()의 경우 width()의 이름으로 생성됩니다.
따라서 set의 결과로 값을 저장 하기 위해 this.width = value;의 값에 대입할 때 width()와 width의 값이 동일하기 때문에 무한루프가 발생하게 됩니다.
작성한 코드 및 에러 메세지
// Getters와 Setters
// 객체지향 프로그래밍 언어 -> G, S
// 클래스 --> 객체(인스턴스)
// 프로퍼티(constructor)
// new Class(a, b, c)
class Rectangle {
constructor(height, width) {
// underscore : private(은밀하고, 감춰야 할 때)
this._height = height;
this._width = width;
}
// width를 위한 getter
get width() {
return this._width;
}
// width를 위한 setter
set width(value) {
// 검증 1 : value가 음수이면 오류!
if (value <= 0) {
//
console.log("[오류] 가로길이는 0보다 커야 합니다!");
return;
} else if (typeof value !== "number") {
console.log("[오류] 가로길이로 입력된 값이 숫자타입이 아닙니다!");
return;
}
this._width = value;
}
// height를 위한 getter
get height() {
return this._height;
}
// height를 위한 setter
set height(value) {
// 검증 1 : value가 음수이면 오류!
if (value <= 0) {
//
console.log("[오류] 세로길이는 0보다 커야 합니다!");
return;
} else if (typeof value !== "number") {
console.log("[오류] 세로길이로 입력된 값이 숫자타입이 아닙니다!");
return;
}
this._height = value;
}
// getArea : 가로 * 세로 => 넓이
getArea() {
const a = this._width * this._height;
console.log(`넓이는 => ${a}입니다.`);
}
}
// instance 생성
const rect1 = new Rectangle(10, 7);
rect1.getArea();
// const rect2 = new Rectangle(10, 30);
// const rect3 = new Rectangle(15, 20);
