前端技术之:如何通过类的属性获取类名
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 }
由此看出A的原型对象constructor属性的值实际上是一个Function,我们进一步获取这个Function的属性描述:
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);
以上输出结果为:true,说明类的实例对象是没有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 } }
说明通过Object.getPrototypeOf获取到的对象原型与类的原型对象是同一个实例。获取到原型对象后,我们就可以获取到对象的类名。
console.info(objProto.constructor.name);
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。