1

I have various ES6 classes, with inheritance. I need to be able to recognize the class, from which the object was instantiated.

I see that Javascript allows us to check, if an object is an instance of a certain calss, using the "instanceof" operator. The problem with this, is that it forces me to make multiple checks, for every possible relevant class.

Isn't there a way in JS to just get the class of the ojbect? For instance, in PHP there's a method for that:

string get_class ([ object $object ] )

Can i achieve something similar in JS?

i.brod
  • 3,993
  • 11
  • 38
  • 74
  • looking for typeof ? eg. `typeof 5` – marmeladze Jul 26 '18 at 10:58
  • 1
    if you have an instance `object` then `object.constructor` will yield the "class" of the object, which is actually a function in JS. for example "the name of the class" is `object.constructor.name` - the name of the initial function which in a `class` declaration is the class name – Ovidiu Dolha Jul 26 '18 at 11:00
  • marmeladze: typeof returns just "object". Ovidiu Dolha: I see. Now i can extract the class name from the string that it returns. – i.brod Jul 26 '18 at 11:02
  • "*I need to be able to recognize the class, from which the object was instantiated.*" - what do you need this for? – Bergi Jul 26 '18 at 12:41

1 Answers1

4

If you have an instance object then object.constructor will yield the "class" of the object, which is actually a function in JS.

For example "the name of the class" is object.constructor.name - the name of the initial function which in a class declaration is the class name

(Just realized this is actually an answer)

Ovidiu Dolha
  • 5,335
  • 1
  • 21
  • 30