How to Get a JavaScript Object’s Class
When working with JavaScript, you may come across situations where you need to determine the class of an object. While JavaScript does not have built-in support for classes like other programming languages, you can still determine the class of an object using various techniques. In this article, we will explore a few methods to accomplish this task.
Method 1: Using the instanceof Operator
The instanceof
operator allows you to check if an object is an instance of a particular class or constructor function. It returns true
if the object is an instance of the specified class, and false
otherwise.
class Person {
constructor(name) {
this.name = name;
}
}
const person = new Person('John');
console.log(person instanceof Person); // true
In the above example, we create a class called Person
and instantiate an object person
from it. By using the instanceof
operator, we can check if person
is an instance of the Person
class, which returns true
.
Method 2: Using the constructor Property
Every JavaScript object has a constructor
property that refers to the constructor function used to create the object. By accessing this property, we can determine the class of an object.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
const car = new Car('Toyota', 'Camry');
console.log(car.constructor.name); // Car
In the above example, we define a class Car
and create an object car
from it. By accessing the constructor.name
property of car
, we can retrieve the name of the constructor function, which in this case is Car
.
Method 3: Using the Object.prototype.toString() Method
The Object.prototype.toString()
method returns a string representation of the object. By calling this method on an object, we can extract the class information from the resulting string.
class Animal {
constructor(name) {
this.name = name;
}
}
const animal = new Animal('Lion');
console.log(Object.prototype.toString.call(animal)); // [object Object]
In the above example, we define a class Animal
and create an object animal
from it. By calling Object.prototype.toString.call(animal)
, we get the string representation of animal
, which is [object Object]
. Although this method does not directly provide the class name, it can still be useful in certain scenarios.
These are a few methods you can use to get the class of a JavaScript object. Depending on your specific requirements, you can choose the most suitable method for your use case.
Remember, JavaScript does not have built-in classes like other languages, but these techniques can help you determine the class of an object in JavaScript.
Happy coding!
Leave a Reply