Home  >  Article  >  What does the instanceof operator do?

What does the instanceof operator do?

小老鼠
小老鼠Original
2023-11-13 15:00:571355browse

The function of the instanceof operator is to determine whether an object belongs to an instance of a certain class or its derived class. It is very useful in object-oriented programming for type checking and polymorphism. The usage of instanceof operator is: object instanceof class. Returns true if the object is an instance of the specified class or its derived class, false otherwise.

What does the instanceof operator do?

Operating system for this tutorial: Windows 10 system, Dell G3 computer.

The instanceof operator is used to check whether an object is an instance of a specific class (or its derived class). Its function is to determine whether an object belongs to an instance of a certain class or its derived class.

The usage method of instanceof operator is: object instanceof class. Returns true if the object is an instance of the specified class or a derived class; otherwise, returns false.

Here is an example:

class Animal {  // ...}class Dog extends Animal {  // ...}const animal = new Animal();const dog = new Dog();console.log(animal instanceof Animal); // trueconsole.log(animal instanceof Dog); // falseconsole.log(dog instanceof Animal); // trueconsole.log(dog instanceof Dog); // true

In the above example, animal is an instance of Animal class, so animal instanceof Animal returns true. But animal is not an instance of the Dog class, so animal instanceof Dog returns false.

And dog is both an instance of the Animal class and an instance of the Dog class, so both dog instanceof Animal and dog instanceof Dog return true.

The instanceof operator can be used to determine whether an object belongs to an instance of a certain class. It is very useful in object-oriented programming and can perform type checking and polymorphic judgment.

The above is the detailed content of What does the instanceof operator do?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn