javascript エラー「TypeError: Attempted to assign to readonly property.」の解決方法 2

javascript エラー「TypeError: Attempted to assign to readonly property.」の解決方法 2

javascriptで、エラー「TypeError: Attempted to assign to readonly property.」が発生した場合の原因と解決方法を記述してます。このエラーは「use strict」の厳格モードのみで発生します。

環境

  • OS macOS Monterey
  • ブラウザ safari 15.5

エラー内容

以下のコードでボタンクリック時に発生。

<input id="txt" type="text" value="foo">
<p id="foo"></p>
<input id="btn" type="button" value="ボタン" />

<script>

'use strict';

function hoge(){
  let bar = txt.value;
  bar.innerHTML = "test";
}

document.getElementById('btn').addEventListener('click', hoge, false);

</script>

エラーメッセージ
※このエラーは「use strict」を使用した厳格モードのみで発生します。

TypeError: Attempted to assign to readonly property.

画像

原因

innerHTMLに、Elementではなく取得したvalueを指定しているため

解決方法

「document.getElementById」を使用する

'use strict';

function hoge(){

  let bar = txt.value;
  document.getElementById(bar).innerHTML = "test";

}

document.getElementById('btn').addEventListener('click', hoge, false);

実行結果

また、safariでは「preventExtensions」で、プロパティの追加を禁止した後にプロパティを追加しようとしても同様のエラーが発生します。

'use strict';

const person = {
  name: 'tanaka'
};

Object.preventExtensions(person);

person.age = 25;

以下のように、classを使用時に、thisで使用している変数が同じ場合にも発生します

class hoge {
  constructor(str) {
    this.str = str; // TypeError: Attempted to assign to readonly property.
  }
 
  get str() {
    return this.str;
  }
 
  foo() {
    console.log(`${this.str}を表示`);
  }
}
 
const bar = new hoge('mebee');
bar.foo();

別名を使用すると、エラーはなくなります。

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