Getting the name of the constructor that an object is created from is something that we’ve to sometimes.
In this article, we’ll look at how to get the name of the constructor that the JavaScript object is created from.
The constructor Property
We can use the constructor
property of an object to get the constructor that it’s created from.
For instance, we can write:
const arr = [1, 2, 3];
console.log(arr.constructor === Array);
Then the console log logs true
since the arr
is created with the Array
constructor.
This can also be used with constructors we create ourselves:
class A {}
const a = new A()
console.log(a.constructor === A);
The console log will also log true
.
Inheritance
If we create an object from a subclass, then we can check if an object created from the current subclass.
For instance, we can write:
class A {}
class B extends A {}
const b = new B()
console.log(b.constructor === B);
Then the console log also logs true
since b
is created from the B
constructor.
constructor
has the name
property to get the constructor name as a string.
For instance, we can write:
class A {}
const a = new A()
console.log(a.constructor.name === 'A');
to compare against the name of the constructor.
The instanceof
Operator
The instanceof
operator also lets us check if an object is created from a constructor.
For instance, we can write:
const arr = [1, 2, 3];
console.log(arr instanceof Array);
Then the console log should log true
since arr
is an array.
However, the Array.isArray
is more reliable for checking if a variable is an array since it works across all frames.
Also, we can write:
class A {}
const a = new A()
console.log(a instanceof A);
to check if a
is an instance of A
.
instanceof
also works with subclasses.
So we can write:
class A {}
class B extends A {}
const b = new B()
console.log(b instanceof B);
And it’ll log true
.
Conclusion
We can use the instanceof
operator and the constructor
property to check if an object is created from the given constructor.