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);