Will it be possible to find out an object's cl

2019-03-03 06:42发布

问题:

When reading the ecmascript-harmony specification I cannot see anything about inspecting instances/objects in regards to find out information about their class and module. What I want to do is to be able to inspect a javascript object (that is an instance of a es6 harmony class) and find out:

  • the name of the class it was instantiated from
  • the name of the module the class was defined in
  • the name of possible super classes and their modules

Does anybody know if this will be possible in es6?

If not is there a reason it would not be possible or preferred?

I can think of a possible issue with a classes not being as "tied" to their module as classes are to packages in other languages, i.e. Java. I.e. what would happen if ClassA is defined in ModuleA and ModuleB imports ClassA to later re-export it?

回答1:

find out the name of the class it was instantiated from

Yes. You can access .constructor.name in ES6.

find out the name of possible super classes

Yes. You can access super classes via the prototype chain.

find out the name of the module the class was defined in

No, that's not possible. A debugger might be able to locate the source file a class was defined in, if the engine supports that, but code does not. Modules and classes are not as static as you might think, and they're certainly no namespaces, so this is useless anyway.