Home > Article > Web Front-end > instanceof usage in js
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.
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:
object
is an instance of constructor
, then ## is returned #true.
.
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
.
constructor
, and true
is returned.
If it cannot be traced, constructor
, and false
is returned.
All objects are instances of
instanceof Object
usually Return true
.
undefined
are not instances of any class, so the instanceof
operator always returns false
.
instanceof
The operator can be used for the following purposes:
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!