Getter & Setter 개념 학습

Hunter Joe·2025년 2월 14일
0
post-thumbnail

Getter와 Setter는 객체 지향 프로그래밍(OOP)에서 사용되는 개념

  • 일종의 메서드 라고 보면 된다.

Getter : 객체의 속성 값을 반환하는 Method
Setter : 객체의 속성 값을 설정, 변경하는 Method

const user = {
  name : "joe",
  age : 20,
}

console.log(user.name); // "joe"

user.name = 'last name'; 
  • 위와 같이 바로 접근하지 말고 getName(), setName() 같은 Method를 통해 경유해서 설정하도록 하는 기법이 Getter와 Setter이다.

const user = {
  name : "joe",
  age : 20,
  
  getName() {
  	return this.name; 
  },
  
  setName(newName) {
	this.name = newName
  },
}

console.log(user.getName()); // "joe"

user.setName('Kim');

this?

  • 객체 내부에서 자기 자신의 속성을 참조할 때는 this를 사용하는 것이 일반적이다.

Getter/Setter 사용 이유

위에서 본 직접적인 수정 혹은 Getter/Setter 함수를 통한 접근 둘 다 결과 값은 같은데 왜 굳이 나눠서 쓰는 걸까?

Getter/Setter를 사용하면 객체 내부 속성에 직접 접근하지 않아 객체의 정보 은닉을 가능하게 해준다.
→ 보안 강화 + 코드 안정성 + 유지 보수성

또한 옳지 않은 값을 넣으려고 할 때 사전 방지가 가능함

Ex)

user.name 속성(프로퍼티)은 문자열외에 값이 들어오면 안되는 경우

const user= {
	name: "joe",
  	age: 20,
  	getName() {
    	return this.name;
    },
	setName(newName) {
      	if (typeof newName !== "string") {
	  		console.error("이름은 문자열 이어야 합니다. ")
          	return
      	} 
    	this.name = newName;
    },
};
console.log(user.getName()); // "joe"

user.setName(123); // "이름은 문자열이어야 합니다."
user.setName("Alice");

console.log(user.getName()); // "Alice"

ES6 이후 Getter/Setter

-ES6 최신 JS부터는 Getter/Setter를 간단하게 정의 할 수 있는 문법이 추가 됨 (get, set)

const user = {
	name: 'joe',
    age: 50,
    
    get userName() {
    	return this.name;
    },
    set userName(newName) {
    	this.name = newName;
    }
}

⚠️ 그런데 이 때의 Getter/Setter는 함수 호출 형식이 아닌 일반 프로퍼티처럼 접근해서 사용된다.
Getter/Setter 메서드를 구현하면 객체엔 userName이라는 가상의 프로퍼티가 생기는데 가상의 프로퍼티는 읽고 쓸 순 있지만 실제로는 존재하지 않는 프로퍼티이다.

접근자 프로퍼티

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

  1. data property (데이터 프로퍼티)
  2. accessor property (접근자 프로퍼티)

데이터 프로퍼티는 객체 내부에 저장된 실제 데이터 값으로서 우리가 일반적으로 프로퍼티라고 부르는 대상이다.

접근자 프로퍼티는 일반적인 프로퍼티와 달리 key-value 를 가지지 않고 Getter/Setter라는 함수를 가지는 특수한 프로퍼티 이다.
→ JS 객체 속성에 접근하듯이 접근자 프로퍼티를 호출하면 함수 호출 문법이 아니더라도 Getter/Setter 함수가 호출되는 것과 같은 것이다.
즉, Getter/Setter 함수 자체가 접근자 프로퍼티 이다.

let person = {
  /* 데이터 프로퍼티 */
  firstName: "John",
  lastName: "Doe",
  
  /* 접근자 프로퍼티 */
  get fullName() {
    return this.firstName + " " + this.lastName;
  },
  set fullName(name) {
    let names = name.split(" ");
    this.firstName = names[0];
    this.lastName = names[1];
  }
};

console.log(person.firstName); // "Jane" 출력
console.log(person.lastName); // "Doe" 출력

console.log(person.fullName); // "John Doe" 출력
person.fullName = "Jane Doe"; // Setter 호출

Getter/Setter 주의점

Getter만 선언

let user = {
  get fullName() {
    return "John Doe";
  }
};

user.fullName = "Test"; 
// ❌ TypeError: Cannot set property 'fullName' of #<Object> which has only a getter

Getter만 정의되어 있다면 JS가 읽기 전용(readonly) 속성을 수정하려고 해서 에러를 발생시킨다.

무한 루프 문제

let user = {
  name: "Inpa",

  get name() {
    return this.name; // ❌ 여기서 무한 루프 발생
  },

  set name(value) {
    this.name = value; // ❌ 여기서도 무한 루프 발생
  }
};
  • get name() 안에서 this.name을 호출 → Getter 다시 호출됨 → 무한 반복
  • set name(value) 안에서 this.name = value; → Setter 다시 호출됨 → 무한 반복

참고 자료

https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-getter-setter-%EB%9E%80

profile
Async FE 취업 준비중.. Await .. (취업완료 대기중) ..

0개의 댓글

관련 채용 정보