javascript エラー「Uncaught TypeError: xxx is not a constructor」の解決方法

javascript エラー「Uncaught TypeError: xxx is not a constructor」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx is not a constructor」が発生した場合の原因と解決方法を記述してます。有効でない「コンストラクター」に対して「new」演算子を使用したりした場合に発生しまう。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 109.0.5414.75

エラー内容

以下の「new」演算子を使用したコードで発生。
※その他のパターンは後述してます。

let hoge = 'hello';

new hoge();

エラーメッセージ(chrome 109)

Uncaught TypeError: hoge is not a constructor

画像

firefox(バージョン108)では、以下のエラーとなります。

Uncaught TypeError: hoge is not a constructor

画像

safari(15.5)では、以下のエラーとなります。

TypeError: "hello" is not a constructor (evaluating 'new hoge()')

画像

原因

「コンストラクター」がないため

解決方法

「hello」を表示する場合は、以下のようにします。

function hoge(){console.log('hello')};

new hoge()

実行結果

その他のエラー

アロー関数を使用

アロー関数や短縮形を使用しても同様のエラーが発生します。

const obj = {
  
  foo: age => {
    this.age = age;
  },
  
  bar(tel) {
    this.tel = tel;
  },

};

const f = new obj.foo(15);
// Uncaught TypeError: obj.foo is not a constructor

const b = new obj.bar(911);
// Uncaught TypeError: obj.bar is not a constructor

通常の関数を使用すればエラーにはなりません。

const obj = {
  
  foo: function Foo(age) {
    this.age = age;
  },
  
  bar: function Bar(tel) {
    this.tel = tel;
  },

};

const f = new obj.foo(15);

const b = new obj.bar(911);

Promise.resolve

「Promise.resolve」に「new」演算子を使用しても発生します。

const hoge = new Promise.resolve('hoge');
// Uncaught TypeError: Promise.resolve is not a constructor

「Promise.resolve」に「new」演算子は使用しない。

const hoge = Promise.resolve('hoge');