javascript エラー「Uncaught TypeError: Cannot set property name of #object which has only a getter」が発生する原因と対処法
- 2020.10.12
- javascript
- javascript

javascriptで、エラー「Uncaught TypeError: Cannot set property name of # which has only a getter」が発生する原因と対処法を記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
エラー内容
以下のコードで発生します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class hoge { constructor(name) { this.name = name; } get name() { return this.name; } foo() { console.log(`${this.name}を表示`); } } const bar = new hoge('mebee'); bar.foo(); |
chromeエラー内容
1 |
Uncaught TypeError: Cannot set property name of #<hoge> which has only a getter |
firefoxの場合
1 |
Uncaught TypeError: setting getter-only property "name" |
原因
別名の変数に値を保存する必要があるため
対処法
ちゃんと別名にしておけば、エラーは表示されません。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class hoge { constructor(name) { this._name = name; } get name() { return this._name; } foo() { console.log(`${this._name}を表示`); } } const bar = new hoge('mebee'); bar.foo(); // mebeeを表示 |
-
前の記事
javascript タイトルを取得または変更する 2020.10.12
-
次の記事
C# 自然対数と常用対数log10を計算する 2020.10.12
コメントを書く