Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does Javascript support reflection and can I get a list of classes an object extends?

Is there a way to get a list of classes an object extends in Javascript? Does Javascript support reflection like this?

I found the Reflect class but I can’t get it any class name information out of it.

var element = document.createElement("textarea");
console.log(element.nodeName); // TEXTAREA
var proto = Reflect.getPrototypeOf(element);
log(proto.name); // error
var element = document.createElement("textarea");
console.log("Name: " + element.nodeName);
var object = Reflect.getPrototypeOf(element);
console.log(object.nodeName); // error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem with your current code is that .nodeName refers to Node.prototype.nodeName, which is a getter – but the getter only works when the this (the instance it’s called on) is an actual element. It doesn’t work when this is something else, like a prototype object.

To get all prototypes, you can keep calling Object.getPrototypeOf and reassigning the prototype, until you reach the end of the prototype chain.

To get the name from each prototype object, assuming they’re constructor prototypes, you can access their .constructor.name properties.

let obj = document.createElement("textarea");
const prototypes = [];
while (obj = Object.getPrototypeOf(obj)) {
  prototypes.push(obj);
}
for (const proto of prototypes) {
  console.log(proto.constructor.name);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading