処理中にクラス名を表示するのはコンストラクタのnameを表示するのが簡単です。
console.log(this.constructor.name);
クラスでは無いトコで使うと
Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'constructor')
になります。
メソッド名が表示したい時はメソッドのnameプロパティが使えます。
class foo {
xxxx() {
const methodName = this.xxxx.name;
console.log(methodName); /* xxxx になる */
}
}
ベタでmethodName = ‘xxxx’で良さそうですが、リファクタリングするとボロボロです。
厄介なのは派生クラスから基底クラスのメソッドを利用している時です。
class hoge extends foo {
className = this.constructor.className;
xxxx() {
console.log(this.className); /* hoge になる */
this.yyyy();
}
}
class foo {
className = this.constructor.className;
yyyy() {
console.log(this.className); /* hoge になる */
}
}
大抵はこれで満足ですが、クラスfooのyyyならfooになって欲しい場合に
class hoge extends foo {
/* className = new hoge().constructor.name; ではループするので、一旦staticなメンバーに入れます */
static className = new hoge().constructor.name;
className = hoge.className;
xxxx() {
console.log(this.className); /* hoge になる */
this.yyyy();
}
}
class foo {
static className = new foo().constructor.name;
className = foo.className;
yyyy() {
console.log(this.className); /* hoge になる */
}
}
と書き込んでも、thisのコンストラクタのnameでは派生クラスの名前が出てきます。
そんな時はクラスのメンバーにclassName=クラス名を書けば解決しそうですが、
class hoge extends foo {
static className = new hoge().constructor.name;
className = hoge.className;
xxxx() {
console.log(this.className); /* hoge になる */
this.yyyy();
}
}
class foo {
static className = new foo().constructor.name;
className = foo.className;
xxxx() {
console.log(this.className); /* hoge になる */
}
}
やはり、thisが強いので、派生クラスの名前が出てしまいますので、自分以外には見えない#classNameを使うと
class hoge extends foo {
static className = new hoge().constructor.name;
className = hoge.className;
#className = hoge.className;
xxxx() {
console.log(this.className); /* hoge になる */
console.log(this.#className); /* hoge になる */
this.yyyy();
}
}
class foo {
static className = new foo().constructor.name;
className = foo.className;
#className = foo.className;
xxxx() {
console.log(this.className); /* hoge になる */
console.log(this.#className); /* foo になる */
}
}
やっと希望どおりになりますが、メンドクサイですし、new すると困る場合には向きません。
クラス名でコンストラクタの名前を取得すると・・・
class hoge {
#className = hoge.constructor.name;
xxxx() {
console.log(this.#className); /* Function になる残念 */
}
}
new した時にコンストラクタが名付けられるっぽい。