Home  >  Article  >  Web Front-end  >  instanceof usage in js

instanceof usage in js

下次还敢
下次还敢Original
2024-05-01 06:00:27840browse

The instanceof operator is used to check whether an object belongs to an instance of a certain class. The syntax is: object instanceof constructor, where object is the object to be checked, and constructor is the constructor of the object whose instance is to be checked. Returns true if object is an instance of constructor, false otherwise.

instanceof usage in js

Usage of instanceof operator in JavaScript

instanceof operator in JavaScript Used to check whether an object belongs to an instance of a class.

Syntax:

<code>object instanceof constructor</code>

Where:

  • object is the object to be checked.
  • constructor is the constructor of the object whose instance is to be checked.

Return value:

  • If object is an instance of constructor, then ## is returned #true.
  • Otherwise return
  • false.

Example:

<code class="js">const person = new Person();

console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
console.log(person instanceof Array); // false</code>

Detailed explanation:

instanceof Operator check# Whether the prototype chain of ##object can be traced back to the prototype attribute of constructor.

If traceable,
    object
  • is an instance of constructor, and true is returned. If it cannot be traced,
  • object
  • is not an instance of constructor, and false is returned.
Note:

All objects are instances of
    Object
  • , so instanceof Object usually Return true.
  • null
  • and undefined are not instances of any class, so the instanceof operator always returns false.
Uses of instance checking:

instanceof

The operator can be used for the following purposes:

Validation Object type (e.g., ensuring that parameters passed to a function are of the required type).
  • Checks whether an object is a subclass of a class (for example, determining whether a
  • Rectangle
  • object is also a Shape object). Perform polymorphic behavior (for example, calling different methods depending on the type of object).

The above is the detailed content of instanceof usage in js. 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