0
0

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 3 years have passed since last update.

JavascriptのES6以降で、親クラスから子クラスのクラス名をstaticメソッド内で取得.

Last updated at Posted at 2020-12-21

「this.name」で親クラスの名前を取得

class.js

class Parent {

 static showName() {
   console.log(this.name);
 }
}


class Child extends Parent {}

Child.showName(); //Child


親クラスに子クラスをインスタンス化するファクトリーメソッドを実装(new this)

class.js

class Parent {

 static new() {
   return new this();
 }
}

class Child extends Parent {}

const ins = Child.new();


子クラス名を取得する際の注意点(static同士でメソッドを呼び出すと、親クラスの名前になる)

  • 以下のケースだと子クラスのクラス名は取得できない。
class.js

class Parent {

 static showName() {
   console.log(Parent._className());
 }
 
 static _className() {
   return this.name;
 }
}


class Child extends Parent {}

Child.showName(); //Parent (Childではない)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?