본문 바로가기
JavaScript

09 -2 게터(getter)와 세터(setter), static 속성과 메소드, 오버라이드

by yj.yoon 2022. 7. 5.

게터(메소드) : 속성 값을 확인할 때 사용하는 메소드 예) get~~()
세터(메소드) : 속성에 값을 지정할 때 사용하는 메소드 예) set~~()

 

<script>
    // 클래스 생성
    class Square {
        #length // 이 위치에 해당 속성을 private 속성으로 사용하겠다고 미리 선언

        constructor (length) {
            this.setLength(length)
        }

        setLength (value) {
            if (value <= 0) {
                throw console.log('길이는 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(`한 변의 길이는 ${square.getLength()} 이다.`)

    // 예외 발생시키기
    square.setLength(-10)
</script>

 

 

- 게터와 세터를 모든 private 속성에 붙이려고 하면 안되고 필요한 경우에만 사용한다.
- private 속성 : 클래스 내부에서만 접근할 수 있는 속성

 

static 속성과 메소드

여러 디자인 패턴을 활용하기 위해 자바스크립트에 추가된 클래스 - 비교적 최근에 추가된 문법으로 static 속성과 static 메소드가 있다. 정적 속성, 정적 메소드라 부르기도 한다.

- 인스턴스를 만들지 않고 사용할 수 있는 속성과 메소드다.

- 일반적인 변수와 함수처럼 사용할 수 있다.

 

class 클래스 이름 {
    static 속성 = 값
    static 메소드 () {}
}

// 클래스 이름.속성
// 클래스 이름.메소드()

 

 

오버라이드

: 부모가 갖고 있는 메소드와 같은 이름으로 메소드를 선언해서 덮어 쓰는 것을 의미한다.

 

<script>
    class Cycle {
        call () {
            this.a()
            this.b()
            this.c()
        }

        a() { console.log('a() 호출')}
        b() { console.log('b() 호출')}
        c() { console.log('c() 호출')}
    }

    class Child extends Cycle {
        // 오버라이드
        a() {
            console.log('자식의 a() 메소드')
        }
    }

    new Child().call()
</script>

 

 

부모에 있던 내용 가져오기

 

<script>
    class Cycle {
        call () {
            this.a()
            this.b()
            this.c()
        }

        a() { console.log('a() 호출')}
        b() { console.log('b() 호출')}
        c() { console.log('c() 호출')}
    }

    class Child extends Cycle {
        a() {
            super.a()
            console.log('자식의 a() 메소드')
        }
    }

    new Child().call()
</script>

 

 

- 자바스크립트의 모든 객체는 toString() 메소드를 갖는데 이유가 자바스크립트가 Object라는 최상위 클래스를 가지며, 어떤 클래스를 만들어도 자동으로 상속받게 되어서 발생하는 현상이다. = toString()이라는 이름으로 Object 클래스의 toString() 메소드를 오버라이드하는 것이 된다.