- How to get the Class Name of an Object in JavaScript
- How to get the Class Name of an Object in JavaScript?
- Solution 1: Get Class Name of an Object Using the constructor Function
- Solution 2: Get Class Name of an Object Using Function inside the class
- Conclusion
- Javascript имя класса объекта
- # Get the Class Name of an Object in JavaScript
- # Get the Class Name of an Object by creating a method on the class
- # Accessing the name property directly on the class
- # Checking if an object was created using a specific class
- # Get the class name of an object by defining a static method
- # Additional Resources
- How to Get a Class Name of an Object
- typeof
- instanceof
- isPrototypeOf
- prototype
- JavaScript Objects
- Related Resources
- How to get the Class name of an Object in JavaScript
- Getting the class name of an object
- Conclusion
How to get the Class Name of an Object in JavaScript
The constructor method in JavaScript is a special method of a class for creating and initializing an object instance of that class. The constructor will have the same name as the class name so we can use this to get the Class Name of an object in Javascript using the constructor name.
How to get the Class Name of an Object in JavaScript?
Before we start exploring the answer to this question, let’s familiarize ourselves with some basic concepts.
Class: They are templates/prototypes for creating objects.
Object: It is an entity that has a particular state and behaviour
Constructor: It is a member function of the class. Invoked during the creation of an object using the new keyword. The purpose of a constructor is to initialize a new object and set values for any existing object properties.
Now that basics are clear let us take a look at different solutions available to find the Class Name of an Object in JavaScript with examples.
Solution 1: Get Class Name of an Object Using the constructor Function
While creating an object of the class, the corresponding constructor is called either explicitly or implicitly. If no constructor is defined, the system invokes the default constructor. This object created can be used to return the class name by calling the name property of the constructor function.
*Fact Check: constructor is a function whereas name is a property
[objectName].constructor.name
Let’s understand this with an example.
class Language <> const l1 = new Language(); console.log(l1.constructor.name);
In the above code snippet, we are creating an empty class named “ Language “. The second line shows constructor invocation for object creation and storing the reference in variable l1 . We can create the object of Language class by using the new keyword and call its default constructor Language() .
Now that we have the object, let’s get the object’s class name. For this, we can use the “ obj. constructor ” function as explained above. It returns a reference to the constructor from which the object got created. It does not refer to the name of the class directly.
To get the specific class name of the object, we have to use the “ name ” property of the constructor function.
Solution 2: Get Class Name of an Object Using Function inside the class
Another way of retrieving the class name of an object can be by creating a function inside the class that will return the object name. We need to use this keyword that will reference to the current object and of which getClassName() method is being called and then it returns it’s class name.
Let’s understand this with an example.
class Language < getClassName() < return this.constructor.name; >> const l1 = new Language (); const objClassName = l1.getClassName(); console.log(objClassName);
In the above example, we are retrieving the object class name through custom functions rather than using the constructors directly.The function “ getClassName() “, as shown in the above example, also uses the Javascript built-in constructor function. Here we use . this keyword so that it returns the current object name in scope.
Firstly, we start by creating and referencing the object of the class Language . Using the reference object, we invoke the method getClassName() .
*Fact check: The approach works for objects created without a constructor function. They have a constructor property that points to the main Object constructor for the specific type.
Let’s have a look at the code below.
console.log([].constructor.name); // Output: Array
Conclusion
We can get the Class Name of an Object in JavaScript by creating an instance of a class and using constructor method’s name property and another approach is by creating our own function and using this.constructor.name inside it.
Both the above-mentioned solutions deliver the same output. The difference lies in the problem statement that we are addressing. We can opt for the first solution when referring to the direct class-object type relationship. The second solution is suitable for referring to class names through a custom function.
Javascript имя класса объекта
Last updated: Dec 28, 2022
Reading time · 3 min
# Get the Class Name of an Object in JavaScript
Access the name property on the object’s constructor to get the class name of the object, e.g. obj.constructor.name .
The constructor property returns a reference to the constructor function that created the instance object.
Copied!class Person > const p1 = new Person(); console.log(p1.constructor.name); // 👉️ Person console.log(Person.name); // 👉️ Person
We accessed the name property on the Object.constructor property.
The Object.constructor property returns a reference to the constructor function from which the object was created.
Copied!class Person > const p1 = new Person(); // ✅ The function (class) that created the object console.log(p1.constructor); // 👉️ [class Person] // ✅ The class name of the object (string) console.log(p1.constructor.name); // 👉️ "Person"
# Get the Class Name of an Object by creating a method on the class
An alternative approach is to create a method on the class to get the class name of the object.
Copied!class Person getClassName() return this.constructor.name; > > const p1 = new Person(); const className = p1.getClassName(); console.log(className); // 👉️ Person
If you need to access the Object.constructor.name property often, create a method that hides it.
Objects that are created without a constructor function have a constructor property that points to the main Object constructor for the specific type.
Copied!console.log(>.constructor.name); // 👉️ Object console.log([].constructor.name); // 👉️ Array
# Accessing the name property directly on the class
You can also access the name property directly on the class to get its name as a string.
Copied!class Person > console.log(Person.name); // 👉️ Person
# Checking if an object was created using a specific class
You can check if an object was created using a specific class in multiple ways.
The obj.constructor.name === Person.name option should be preferred when you minify your code for production.
Copied!class Person > const p1 = new Person(); if (p1.constructor.name === 'Person') // 👇️ this runs console.log("The object's constructor is Person"); > // -------------------------------------------------- // ✅ If you minify your code for production, do this if (p1.constructor.name === Person.name) // 👇️ this runs console.log("The object's constructor is Person"); >
The first if statement accesses the constructor.name property to get the class name of the object and compares it to the string «Person».
Copied!class Person > const p1 = new Person(); if (p1.constructor.name === 'Person') // 👇️ this runs console.log("The object's constructor is Person"); >
This would work most of the time, however, if possible, it is better to compare the object’s class name to Person.name .
Copied!class Person > const p1 = new Person(); // ✅ If you minify your code for production, do this if (p1.constructor.name === Person.name) // 👇️ this runs console.log("The object's constructor is Person"); >
If you minify your code for production, the name of the class might change. This isn’t an issue when you access the name property on the class in the comparison.
# Get the class name of an object by defining a static method
You can also define a static method that you can access directly on the class to get the class name of an object.
Copied!class Person static getClassName() return 'Person'; > getClassName() return Person.getClassName(); > > const p1 = new Person(); const className = p1.getClassName(); console.log(className); // 👉️ Person console.log(Person.getClassName()); // 👉️ Person
The static keyword defines a static method or field. Static methods cannot be directly accessed on instances of the class and must be accessed on the class itself.
Our static method returns the string Person and our instance method calls the static method to return the same value.
If you need to check if an object is an instance of a class at runtime, use the instanceof operator.
Copied!class Person > const p1 = new Person(); class Animal > console.log(p1 instanceof Person); // 👉️ true console.log(p1 instanceof Animal); // 👉️ false
The instanceof returns true if the prototype property of a constructor appears in the prototype chain of an object and false otherwise.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to Get a Class Name of an Object
As there is no direct getClass() method in JavaScript to get the object’s class name, you can use several options which will help you solve this problem.
typeof
The typeof operator returns a string that indicates the type of the unevaluated operand:
Javascript typeof operator return a string
function Func() <> let func = new Func(); typeof Func; // == «function» typeof fonc; // == «object» console.log(typeof Func); console.log(typeof func);
instanceof
The instanceof operator is used for checking whether the constructor’s prototype property appears anywhere in the object’s prototype chain. Use the name property of the constructor function to get the name of the class:
Javascript instanceof operator check the constructor’s prototype property
function Func() <> let func = new Func(); console.log(Func.prototype.isPrototypeOf(func)); // == true console.log(func instanceof Func); // == true console.log(func.constructor.name); // == «Func» console.log(Func.name); // == «Func»
isPrototypeOf
The isPrototypeOf() method is used to check whether an object exists in another object’s prototype chain:
Javascript isPrototypeOf method check an object exists in another object’s prototype
function Func() <> let func = new Func(); console.log(Func.prototype.isPrototypeOf(func)); // == true
prototype
You can use the prototype property for getting the name of the object class:
Javascript prototype property get the name of object class
function Func() <> let func = new Func(); Func.prototype.bar = function (x) < return x + x; >; console.log(func.bar(11)); // == 22
JavaScript Objects
The Object class represents one of the data types in JavaScript. It is used to store various keyed collections and complex entities. Almost all objects in JavaScript are instances of Object; a typical object inherits properties (as well as methods) from Object.prototype, though they may be overridden.
Related Resources
- How to Count the Number if Keys/Properties of a JavaScript object
- How to Merge Properties of Two JavaScript Objects Dynamically
- How to Check if an Object has a Specific Property in JavaScript
- How to Get the First Key Name of a JavaScript Object
- How to Check if a Value is an Object in JavaScript
- How to Check if a Key Exists in JavaScript Object
- How to Check if JavaScript Object is Empty
- How to Clone a JavaScript Object
- How to Display a JavaScript Object
- JavaScript Prototype Methods, Objects Without __proto__
- JavaScript Class Checking: «instanceof»
- JavaScript Data Types
- Javascript Objects
- JavaScript F.prototype
How to get the Class name of an Object in JavaScript
JavaScript supports object-oriented programming, which means that you can create classes and objects, and use them to store data.
One useful thing to be able to know from an object is the name of the class it was created from.
In this post, we’ll learn how you can get the class name of an object in JavaScript.
Getting the class name of an object
First let’s start with a class and an object created from it.
const triangle = new Shape();
Given the object triangle , we can get the class name of it using the constructor property, which returns a reference to the constructor function that created the object, then using the name property to get the name of the class.
const triangle = new Shape(); console.log(triangle.constructor.name);
The reason this works is you can use the constructor property to get the class of an object, which includes the name, along with other properties.
Because most things in JavaScript are objects, they will therefore have a valid constructor property.
Conclusion
In this post, we’ll learn how you can get the class name of an object in JavaScript by using the constructor property.
This is useful because it allows you to get the name of the class that created an object, which can be useful for debugging.
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Give feedback on this page , tweet at us, or join our Discord !