Front end technology: how to get the class name through the property of the class

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

Get the constructor property of the prototype object of the class:

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

The results are as follows:

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

From this, we can see that the value of the constructor property of the prototype object of A is actually A Function. We can further obtain the property description of this Function:

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

Or directly obtain:

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

The results are as follows:

{
  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 
  } 
}

From this, we can get the class name through the prototype.constructor.name property of the class.

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

We have known how to get the name of a class through its properties, but it is not feasible to use this method directly for instance objects of a class, because the object instance of a class does not have the prototype property.

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

The above output is: true, indicating that the instance object of the class has no prototype attribute. But we can get the prototype of the object through 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));

The output of the above code is:

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 } }

The object prototype obtained through Object.getPrototypeOf is the same instance as the prototype object of the class. After getting the prototype object, we can get the class name of the object.

console.info(objProto.constructor.name);

Tags: Front-end Attribute

Posted on Tue, 05 Nov 2019 08:42:16 -0800 by deathrider