フロントエンド技術:どのようにクラス名属性クラスを介して取得します

class A {
  constructor(a, b = 'bbb', c = 1) {
    this.a = a;
    this.b = b;
    this.c = c;
  }
}

プロトタイプオブジェクトのconstructorプロパティクラスを取得します:

const desc3 = Object.getOwnPropertyDescriptor(A.prototype, 'constructor');
console.info(desc3);

結果は以下の通りであります:

{ 
  value: [Function: A],
  writable: true,
  enumerable: false,
  configurable: true 
}

これは、属性の値は、プロトタイプオブジェクトのコンストラクタは、実際に関数であることを示している、我々はさらに、この機能で説明するプロパティを取得します:

console.info(Object.getOwnPropertyDescriptors(desc3.value));

または直接アクセスします:

console.info(Object.getOwnPropertyDescriptors(A.prototype.constructor));

結果は以下の通りであります:

{
  length: { 
    value: 1,
    writable: false,
    enumerable: false,
    configurable: true 
  },
  prototype: { 
    value: A {},
     writable: false,
     enumerable: false,
     configurable: false 
  },
  name: { 
    value: 'A',
    writable: false,
    enumerable: false,
    configurable: true 
  } 
}

これは、あなたは私たちがprototype.constructor.nameプロパティクラスでクラス名を取得することができ、見ることができます。

console.info(A.prototype.constructor.name);

このメソッドを直接使用してクラスのインスタンスオブジェクトが動作しないように、オブジェクトがクラスのprototypeプロパティのインスタンスではありませんので、我々はすでに、プロパティを通じてクラスの名前を取得する方法を知っているが、。

console.info(undefined == new A().prototype);

上記の出力:真は、プロパティを試作されていないオブジェクト・クラスの一例を示す図です。しかし、我々はObject.getPrototypeOfによってプロトタイプに対応するオブジェクトを取得することができます。

const instance = new A();
const objProto = Object.getPrototypeOf(instance);
console.info(objProto === A.prototype);
console.info(Object.getOwnPropertyDescriptors(objProto));
console.info(Object.getOwnPropertyDescriptors(objProto.constructor));

上記のコードの出力:

true
{ constructor:
{ value: [Function: A],
writable: true,
enumerable: false,
configurable: true } }
{ length:
{ value: 1,
writable: false,
enumerable: false,
configurable: true },
prototype:
{ value: A {},
writable: false,
enumerable: false,
configurable: false },
name:
{ value: 'A',
writable: false,
enumerable: false,
configurable: true } }

DESCRIPTION Object.getPrototypeOfオブジェクトプロトタイプとプロトタイプオブジェクトが取得したクラスの同じインスタンスです。プロトタイプオブジェクトを取得した後、我々は、オブジェクトのクラス名を取得することができます。

console.info(objProto.constructor.name);

おすすめ

転載: blog.51cto.com/14565733/2447805