あなたはconstructor
にname
からそれを得ることができます。
console.log(object.constructor.name);
デフォルトでは、constructor
は、オブジェクトを作成するために使用するコンストラクタ関数です。オブジェクトのプロトタイプから継承しています。 name
はその名前です。
あなたはそのプロトタイプに1をシャドーイング、インスタンス自体でconstructor
プロパティーである可能性があるについて少し被害妄想になりたい場合は、あなたが使用できます。
console.log(Object.getPrototypeOf(object).constructor.name);
ライブ例:
class Class1 {
}
const c1 = new Class1();
console.log(c1.constructor.name); // "Class1"
class Class2 {
constructor() {
this.constructor = "I'm special";
}
}
const c2 = new Class2();
console.log(Object.getPrototypeOf(c2).constructor.name); // "Class2"
しかし、JavaScriptを指定TC39委員会は幸せな電子だったことに注意してくださいnough新しい約束そのthen
とcatch
リターンを構築するときに、あなたもあれば、あなた自身に出ないだろうので、(hereを行くと、インスタンスからconstructor
を読み込むステップを参照)Promise
秒でインスタンスのconstructor
プロパティを使用しますそれを使用しました。彼らはインスタンスのプロトタイプには行きません。
しかし、それは道に迷ってあなたを導くためにするために、プロトタイプのconstructor
プロパティもでマックすることができますので、はい、ちょうど完全を期すため、あなたはそれのためのプロトタイプに行く場合でも、それは、まだ可能です:
class Example {
}
Example.prototype.constructor = Object; // Why would anyone do this? People are weird.
const e = new Example();
console.log(Object.getPrototypeOf(e).constructor.name); // "Object"
class Example {
}
// Why would someone do this? People are weird.
Object.defineProperty(Example, "name", {
value: "flibberdeegibbit"
});
const e = new Example();
console.log(Object.getPrototypeOf(e).constructor.name); // "flibberdeegibbit"
:
これは、関数にname
を再定義することも可能です
だから...注意してください。 (class
構文のように)機能name
プロパティは、ES2015のように、新しいあること
注意。蒸散器でclass
の構文を使用している場合は、name
が正しく設定されている場合とされていない場合があります。
これは何のために必要ですか?アプリケーションに実際の目的があるはずであれば、明示的な 'getClassName'メソッドがあります。 – Bergi
可能な複製[オブジェクトのクラスとモジュールをecmascript-harmonyで見つけることができるようになる](https://stackoverflow.com/q/19279232/1048572) – Bergi