IT/JS

Getter와 Setter

프티 2022. 7. 1. 16:25
반응형

객체의 프로퍼티에는 두 종류로 나뉜다.

 

1. 데이터 프로퍼티

2. 접근자 프로퍼티

 

우리가 지금까지 사용했던 프로퍼티는 데이터 프로퍼티이다.

접근자 프로퍼티는 본질이 함수이며, 값을 획득(getter)하고 설정(setter)하는 역할을 한다.

 

객체 리터럴 안에서 getter와 setter는 각각 get과 set으로 나타낼 수 있다.

 

let user = {
  name: "John",
  surname: "Smith",

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

alert(user.fullName); // John Smith

위 코드를 보면 get 프로퍼티를 일반 프로퍼티처럼 호출하여 사용할 수 있다.

그 뒤의 로직은 getter 메서드가 처리하기 때문이다.

 

let user = {
  name: "John",
  surname: "Smith",

  get fullName() {
    return `${this.name} ${this.surname}`;
  },

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  }
};

// 주어진 값을 사용해 set fullName이 실행됩니다.
user.fullName = "Alice Cooper";

alert(user.name); // Alice
alert(user.surname); // Cooper

위와 같이 setter 메서드를 구현하면 해당 프로퍼티에 새로운 값을 할당할 수 있다.

 

이렇게 getter와 setter 메서드를 구현하면 객체엔 fullName이라는 가상의 프로퍼티가 생긴다.

가상의 프로퍼티는 읽고 쓸 수 있지만 실제로 존재하지는 않는다.

반응형

'IT > JS' 카테고리의 다른 글

기본 매개변수 (Default Parameters)  (0) 2021.09.12
fetch API와 then 메서드  (0) 2021.09.09
클로저  (0) 2021.09.07
Recursion  (0) 2021.08.30
콜백 함수  (0) 2021.08.30