getter와 setter (Getters and Setters)

getter와 setter (Getters and Setters)

자바스크립트(JavaScript)에서 객체의 속성을 다룰 때, 속성 값을 읽거나 설정하는 동작을 제어하고 싶을 때가 있다. 이런 경우에 gettersetter를 사용한다. getter와 setter의 개념, 정의 방법, 활용 사례를 예제로 확인한다.


getter는 속성 값을 가져오는 함수이고, setter는 속성 값을 설정하는 함수다. 이들은 Object.defineProperty나 객체 리터럴 문법으로 정의된다.


getter와 setter란 무엇인가?

getter와 setter는 객체 속성에 접근하거나 수정할 때 호출되는 특수 메서드다. 속성처럼 보이지만 내부적으로 함수로 동작한다. 기본적인 예제를 보자:

const obj = {
    _name: "철수",
    get name() {
        return this._name;
    },
    set name(value) {
        this._name = value;
    }
};
console.log(obj.name); // "철수"
obj.name = "영희";
console.log(obj.name); // "영희"

위 코드에서 get name은 속성 값을 반환하고, set name은 값을 설정한다.


getter와 setter의 정의 방법

getter와 setter는 두 가지 주요 방식으로 정의된다.


1. 객체 리터럴 문법

객체를 정의할 때 직접 getter와 setter를 추가한다:

const user = {
    _age: 25,
    get age() {
        return this._age;
    },
    set age(value) {
        if (value >= 0) this._age = value;
    }
};
user.age = 30;
console.log(user.age); // 30
user.age = -5; // 무시됨
console.log(user.age); // 30

2. Object.defineProperty

속성을 동적으로 정의한다:

const obj2 = { _data: 10 };
Object.defineProperty(obj2, "data", {
    get: function() {
        return this._data;
    },
    set: function(value) {
        this._data = value * 2;
    }
});
console.log(obj2.data); // 10
obj2.data = 5;
console.log(obj2.data); // 10

getter와 setter의 동작 방식

getter는 속성에 접근할 때 호출되고, setter는 속성에 값을 할당할 때 호출된다. 속성처럼 사용되지만 내부 로직을 포함할 수 있다.


예제를 통해 동작을 확인한다:

const person = {
    _firstName: "철수",
    _lastName: "김",
    get fullName() {
        return `${this._firstName} ${this._lastName}`;
    },
    set fullName(value) {
        const [first, last] = value.split(" ");
        this._firstName = first;
        this._lastName = last;
    }
};
console.log(person.fullName); // "철수 김"
person.fullName = "영희 박";
console.log(person.fullName); // "영희 박"

사용 사례

getter와 setter를 활용한 몇 가지 예제를 확인한다.


1. 데이터 유효성 검사

값을 설정할 때 조건을 확인한다:

const product = {
    _price: 1000,
    get price() {
        return this._price;
    },
    set price(value) {
        if (typeof value === "number" && value > 0) {
            this._price = value;
        }
    }
};
product.price = 2000;
console.log(product.price); // 2000
product.price = -500; // 무시됨
console.log(product.price); // 2000

2. 계산된 속성

동적으로 값을 계산한다:

const rectangle = {
    width: 5,
    height: 10,
    get area() {
        return this.width * this.height;
    }
};
console.log(rectangle.area); // 50
rectangle.width = 6;
console.log(rectangle.area); // 60

3. 속성 보호

내부 데이터를 간접적으로 관리한다:

const account = {
    _balance: 10000,
    get balance() {
        return this._balance;
    },
    set balance(value) {
        if (value >= 0) this._balance = value;
    }
};
console.log(account.balance); // 10000
account.balance = -1000; // 무시됨
console.log(account.balance); // 10000

4. 클래스에서의 사용

클래스에서도 getter와 setter를 정의할 수 있다:

class Person {
    _name;
    constructor(name) {
        this._name = name;
    }
    get name() {
        return this._name;
    }
    set name(value) {
        this._name = value;
    }
}
const p = new Person("철수");
console.log(p.name); // "철수"
p.name = "영희";
console.log(p.name); // "영희"

성능과 한계

장점

- 제어 가능: 속성 접근과 수정을 세밀하게 관리한다.

- 가독성: 속성처럼 보이는 문법으로 코드가 깔끔하다.


한계

- 오버헤드: 단순 속성보다 실행 속도가 느릴 수 있다.

- 재귀 호출 위험: getter와 setter 내부에서 동일한 속성을 호출하면 무한 루프가 발생한다.

재귀 호출 방지를 위해 내부 변수(예: _name)를 사용하는 습관을 들이는 것이 좋다.


마무리

getter와 setter는 자바스크립트에서 속성을 제어하는 도구다. 정의 방법과 활용 사례를 예제로 다뤘다.


+ Recent posts