您的位置:首页 > Web前端

前端技术之:如何通过类的属性获取类名

2019-11-05 05:22 1611 查看
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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: