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
- HTTPError
- HTMLElement
- NodeList
- undefined
1 Answer 1
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.
3 Comments
instance of which this belongs to?.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);.)