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

Time:08-24

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

CodePudding user response:

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

  • Related