A summary of the usage of the instanceof operator in JavaScript

  • 2020-03-29 23:52:01
  • OfStack

The instanceof operator in JavaScript returns a Boolean value indicating whether an object is an instanceof a particular class.

Usage:
Result = object instanceof class
Where result is a required option. Any variable.
Object is required. Any object expression.
Class is required. Any defined object class.

instructions
The instanceof operator returns true if object is an instanceof class. Returns false if object is not an instance of the specified class, or if object is null.

The instanceof operator in JavaScript
The following example illustrates the use of the instanceof operator.


function objTest(obj){
   var i, t, s = "";   //Create variables.
   t = new Array();   //Create an array.
   t["Date"] = Date;   //Populate the array.
   t["Object"] = Object;
   t["Array"] = Array;
      for (i in t)
      {
         if (obj instanceof t[i])   //Check obj's class.
         {
            s += "obj is an instance of " + i + "/n";
         }
         else 
         {
            s += "obj is not an instance of " + i + "/n";
         }
   }
   return(s);   //Returns a string.
}
var obj = new Date();
response.write(objTest(obj));


Related articles: