LoginSignup
2
2

More than 3 years have passed since last update.

TypeError: Class constructor cannot be invoked without 'new'

Posted at

const class

エラーの出たJavaScript

const A = class {
  constructor(_a) {
    this.a = _a;
  }
}

const B = class extends A {
  constructor(_b) {
    super(_b);
  }
}

(() => {
  var b = new B("test");
  console.log(b);
})();

とあるJavaScriptを試したところ「TypeError: Class constructor cannot be invoked without 'new'」が出た。

エラーの原因は何? :thinking:

普通のclass

エラーの出ないJavaScript

class A {
  constructor(_a) {
    this.a = _a;
  }
}

class B extends A {
  constructor(_b) {
    super(_b);
  }
}

(() => {
  var b = new B("test");
  console.log(b);
})();

普通によく見るclassならエラーが出ない。

判明した原因とは

原因

const B = class extends A {}()

後ろの無名関数の即時関数とくっついてnew A()し損ねたと判定された。

constの後ろに「;」をつけてやれば解決。


提案

const classを使わないようにしよう。
知らないだけかもだがあまり見ないと思う :unamused:

「;」を省略しないようにしよう。
ブックマークレットが動かなくなるし今回のようなこともある。

自戒と反省を込めて :relaxed:

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2