javascript エラー「Uncaught TypeError: Illegal invocation」がオブジェクトを変数代入時に発生した場合

javascript エラー「Uncaught TypeError: Illegal invocation」がオブジェクトを変数代入時に発生した場合

javascriptでオブジェクトを変数代入時にエラー「Uncaught TypeError: Illegal invocation」の発生原因と対処法を記述してます。

環境

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

エラー内容

「document.getElementById」に、変数代入時に発生

<p id="hoge"></p>

<script>

const obj = document.getElementById;
obj('hoge').textContent = "mebee";

</script>

chrome103.0.5060.114上で、以下のエラーが発生

Uncaught TypeError: Illegal invocation

firefoxでは、以下のエラーとなります。

Uncaught TypeError: 'getElementById' called on an object that does not implement interface Document.

IEでは、以下となります。

SCRIPT65535: オブジェクトの呼び出しが無効です

safari15.5だと以下となります。

TypeError: Can only call Document.getElementById on instances of Document

原因

javascriptでは、ネイティブ関数を変数に代入しようとすると発生してしまいます。

対処法

直接参照しない

※引数「x」は、任意で指定してます。基本的に、使用できる名称であれば問題ないです。

<p id="hoge"></p>

<script>

const obj = function(x){return document.getElementById(x)};

obj('hoge').textContent = "mebee";

</script>

ちなみに、アロー関数で書くと以下となります。

const obj = x => document.getElementById(x);

obj('hoge').textContent = "mebee";

同じネイティブ関数である「document.write」の場合も、同じように記述できます。

const obj = x => document.write(x);

obj('hello');