본문 바로가기
Language/JavaScript

[Class] 게터와 세터

by 싯벨트 2022. 12. 17.
728x90

#getter 

기존 혹은 새로운 속성에 원하는 속성 또는 메서드를 리턴한다

단, 기존 속성을 사용하는 경우, 같은 변수명을 대입하면 안 된다. 

 - 일반적으로 언더바(private 변수 의미)를 prefix로 사용한다.

 - ex. 예시 코드, _width & _height

 

1. 속성 형성 및 메서드 리턴

get area() 처럼 생성자 함수를 통해 this에 바인딩되어 있지 않은 속성값에 대해 Rectangle.prototype 에 있는 메서드(calcArea)를 리턴하며 매개변수에 따라 계산된 값을 할당할 수 있다.

 

#setter

게터에서 가져온 값에 대한 처리를 한다. 

해당 속성에 할당된 값을 사용하고 싶은 경우, 매개변수를 사용한다. (함수와 동일한 방법으로 사용)

- ex. 예시코드 set width(value){ ... }

 

1. 조건문 내부 return 차이

return을 기재한 경우, 메시지 반환 후 값을 세팅하지 않고 setter 메서드를 나가게 되므로, undefined 가 할당되며, area 값이 계산되지 않는다.

class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
    
    get area() {
        return this.calcArea();
    }
    
    calcArea() {
      return this.height * this.width;
    }

    get width() {
        return this._width
    }

    set width(value){
        if(value < 0){
            console.log('width must be positive')
            return;
        }
        this._width = value
    }

    get height() {
        return this._height
    }

    set height(value){
        if(value < 0){
            console.log('width must be positive')
        }
        this._height = value
    }
}

const rectangle = new Rectangle(-20, 10);

console.log(typeof rectangle.area, rectangle.area) //number -200
console.log(typeof rectangle.calcArea) // function
console.log(rectangle.width) // 10
console.log(rectangle._width) // 10
console.log(rectangle.height) // -20

참고자료