19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSのクラス名をゲットする

Last updated at Posted at 2016-10-11

EventEmitterとかのEvent名にクラス名を仕込みたいなと思って、自分のクラス名を取得する方法を考えた。
シンプルに this.constructor.name でよかった。extendsした時の挙動がよくわからなかったので試した。

code.js
class Base {
  constructor() {
    console.log("Base"); // line 1
    console.log(this.constructor.name); // line2
  }

  getClassName() {
    console.log(this.constructor); // line4
    console.log(this.constructor.name); // line5
  }
}

class Something extends Base {
  constructor() {
    super()
    console.log("Something"); // line 3
  }
}

var o = new Something();
o.getClassName();
result
Base
Something
Something
[Function: Something]
Something

サンキューです

19
19
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
19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?