In JavaScript, the `instanceof` operator is used 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 constructor, and `false` otherwise.
Here's the basic syntax of the `instanceof` operator:
object instanceof constructor
Here's an example demonstrating the use of `instanceof`:
// Constructor functionfunction Car(make, model) {this.make = make;this.model = model;}// Creating an object using the constructorlet myCar = new Car("Toyota", "Camry");// Checking if the object is an instance of the Car constructorlet isCar = myCar instanceof Car;console.log(isCar); // Outputs: true
In this example, `myCar instanceof Car` returns `true` because `myCar` was created using the `Car` constructor.
You can also use `instanceof` with built-in objects and classes:
let arr = [1, 2, 3];let isArr = arr instanceof Array;console.log(isArr); // Outputs: truelet today = new Date();let isDate = today instanceof Date;console.log(isDate); // Outputs: true
In these examples, `arr instanceof Array` checks if `arr` is an instance of the `Array` constructor, and `today instanceof Date` checks if `today` is an instance of the `Date` constructor.
It's important to note that `instanceof` checks the entire prototype chain, so if an object is an instance of a class, it will also be an instance of all its ancestor classes in the prototype chain.
class Animal {}class Dog extends Animal {}let myDog = new Dog();console.log(myDog instanceof Dog); // Outputs: trueconsole.log(myDog instanceof Animal); // Outputs: true
In this example, `myDog instanceof Animal` returns `true` because `Dog` extends `Animal`.
Social Plugin