0

Is there any new method or approach to find the instance ( parent Object class name) in es6?

just like we have typeof <entity> and it returns the type

and the keyof in typescript

can we check somehow that this is the instance of which Object?

dummy code

instanceof <entity>

return something like that

  1. HTTPError
  2. HTMLElement
  3. NodeList
  4. undefined

1 Answer 1

4

You can use the object's constructor property (which is usually inherited from its prototype) if the object in question has one (not all will; ones created via constructor functions usually will).

Example:

const dt = new Date();
console.log(dt.constructor === Date); // true

For instance, in ES2015+, Promise, Array, and others use constructor when creating new objects of the same type (for instance, Promise's then uses it, Array's slice uses it, etc.) so that those operations are friendly to subclasses. Gratuitous subclass example:

class MyArray extends Array {
}
const a = new MyArray("a", "b", "c");
const b = a.slice(1);              // Creates new MyArray
console.log(b.join(", "));         // "b, c"
console.log(b instanceof MyArray); // true

In general, though, in JavaScript we tend to prefer duck typing to constructor or instanceof checks.

Sign up to request clarification or add additional context in comments.

3 Comments

my question is what if I don't know the instance of which this belongs to?
@pro.mean - Right, that's .constructor. It gives you the function that's associated with the object as its constructor. You don't have to have pre-existing knowledge of the function. (And if you want its name, on ES2015+ engines, use its .name property: console.log(obj.constructor.name);.)
Thank you, magician. that is my desired answer moreover the main answer is wider and in depth. thanks for the concise detail.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.