[JS] Maximum call stack size exceeded 해결 | class getter setter 이해하기

HongBeen Lee·2021년 9월 28일
2

Java Script

목록 보기
4/5
post-thumbnail

Class setter, call stack 에러발생

자바스크립트에서 클래스를 만들 때 다음과 같이 만들었다고 해보자.

  • name을 값으로 입력받는 class St 를 만들었다.
  • 입력받은 name을 setter로 넘겨 값을 업데이트해주려고 한다.
  • call stack의 범위를 넘어선다는 에러가 발생했다.

무한재귀✨ 때문이다.

이 때 call stack에러는 무한재귀에 빠졌기 때문에 발생한다.

constructor() 내부의 this.name=name; 코드가 set name()을 호출한다.

메모리에 name을 바로 할당하여 업데이트하지 않고 setter를 호출 하는 것이다!

호출된 setter내부에서 this.name=name; 코드가 똑같이 존재하므로 또 다시 set name()을 호출하는 무한재귀에 빠지게된다.


해결방법✨

이를 해결하기 위해 구글을 뒤져본 결과!

다들 _(underscore)를 적용하라고 한다.

  • 아래와 같이 setter내부에 this._name=name; 로 수정했다.
  • 보다싶이 재귀에 빠지지 않게되었다.
  • _를 붙이면 private 혹은 내부적인 속성이라고 명시하는 것이다.
  • 다시말하면 기술적으로 hiny._name 접근이 가능하긴 하다.
  • 자바스크립트의 Privacy 코드컨벤션 중 하나로, 접근이 가능하지만 외부에서 가져다 쓰지말자는 의미이다.

That's a very common theme in JS. Privacy by convention.

By prefixing the property with one or multiple underscores you signal that this is some private or internal property and not part of the public API for this class, and therefore consumers of these objects should stay away from these properties.


이게 왜... 되지..❓

이제는 호출된 setter내부에서 this._name=name; 코드에 의해 set name()이 다시 호출되지 않는다.

하지만 내가 저장한 this.name을 얻으려고 입력하면,
undefined 라고 뜬다.


당연함. setter에서 _name이라고 저장했음.

다시한번 강조하지만,
this.name=name; 코드에서 바로 메모리에 올리는 것이 아니다!
이 코드는 setter를 호출하고 값을 넘겨주는 역할을 한다!

그래서 이제 getter이 필요한거다.
이제 get name()을 싸악 끼워넣어주면?

class St{
  constructor(name){
    this.name=name;
  }
  get name(){
  return this._name;
  }
  set name(value){
    this._name=name;
  }
}

this.name이라고 입력하면 원하는 이름을 얻어낼 수 있다.

즉, 실제 내부에는 _name이라고 저장되어 있고 name은 저장된 _name에 접근하기 위한 키 역할을 하는 것이다.


📌결론!

  • this.name=name;을 통해 setter를 호출, 값을 저장
  • this.name;으로 getter로 접근해서 저장된 _name을 싸악 꺼내주는 것이다.


틀린부분이 있으면 언제든 알려주세요........😂
profile
🏃🏻‍♀️💨

1개의 댓글

comment-user-thumbnail
2023년 4월 17일

감사합니다!!

답글 달기