Javascript get object class name: To obtain the class name of the object, such as obj.constructor.name, access the name property on the object’s constructor.
The constructor property returns a reference to the constructor function that created the instance object.
index.js:
// @@ Create a contsructor say Employ
class Employ {}
// Create an object for the above class using the new keyword
const obj = new Employ();
// Get the name of the contsructor using the Object.constructor.name attribute by applying it on the above object
console.log(obj.constructor.name);
Output:
Employ
Explanation:
Here we accessed thenameproperty on theObject.constructorproperty.
The Object.constructor property returns a reference to the constructor function, that was used to create the object.
// @@ Create a class say Employ
class Employ {}
// Create an object for the above class using the new keyword
const obj = new Employ();
// Get the reference to the constructor using the constructor attribute by applying it on the above object
console.log(obj.constructor);
Output:
[Function: Employ]
Javascript get class name of object: Another option is to create a method on the class that returns the object’s class name.
// Create a class say Employ
class Employ {
// Inside the class create a function say getClassName()
// which returns the name of the class using the constructor.name property
getClassName() {
return this.constructor.name;
}
}
// Create an object for the above class using the new keyword
const obj = new Employ();
// Apply getClassName() function on the above object
// to get the class name of the above created class
const class_name = obj.getClassName();
// Print the class name
console.log(class_name);
Output:
Employ
If you frequently need to access the Object.constructor.name property, you can create a method to hide it.
NOTE:
All objects (excluding those created with Object.create(null)) have a constructor property.
Objects that are created without a constructor function have a constructor property that refers to the main/primary Object constructor for the particular type.
index.js:
// Get the type of the contrusctor using the constructor.name
// Property. Here {} represents object hence it returns Object
console.log({}.constructor.name);
// Get the type of the contrusctor using the constructor.name
// Property. Here [] represents an array hence it returns Array
console.log([].constructor.name);
Output:
Object Array