javascript エラー「Uncaught RangeError: Maximum call stack size exceeded」が発生する原因と対処法

javascript エラー「Uncaught RangeError: Maximum call stack size exceeded」が発生する原因と対処法

javascriptで、エラー「Uncaught RangeError: Maximum call stack size exceeded」が発生する原因と対処法を記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.66

エラー内容

以下のコードを実行時に発生しました。

class hoge {
  constructor() {
    console.log('コンストラクタを実行');
  }

  set name(name) {
    this.name = name;
  }
 
  get name() {
    return this.name;
  }
 
  foo() {
    console.log(`${this.name}を表示`);
  }
}
 
const bar = new hoge();
bar.name='mebee';
bar.foo();

chrome103.0.5060.66エラー内容

Uncaught RangeError: Maximum call stack size exceeded

firefox102の場合

Uncaught InternalError: too much recursion

safari15.5の場合

RangeError: Maximum call stack size exceeded.

原因

Setterには、別名の変数で値を保存しないと再帰的になってしまうため

対処法

ちゃんと別名にしておけば、エラーは表示されません。

class hoge {
  constructor() {
    console.log('コンストラクタを実行');
  }

  set name(name) {
    this._name = name;
  }
 
  get name() {
    return this._name;
  }
 
  foo() {
    console.log(`${this._name}を表示`);
  }
}
 
const bar = new hoge(); // コンストラクタを実行
bar.name='mebee';
bar.foo(); // mebeeを表示