Example of using instanceof operator in JavaScript

  • 2021-06-28 08:44:39
  • OfStack

The instanceof operator can be used to determine whether the prototype attribute of a constructor exists on the prototype chain of another object to be detected.

Example 1: General usage

A instanceof B: Detects whether B.prototype exists in the prototype chain of parameter A.


function Ben() {

}
var ben = new Ben();
console.log(ben instanceof Ben);//true

Instance 2: Determine whether an instance belongs to its parent class in inheritance


function Ben_parent() {}

function Ben_son() {}

Ben_son.prototype = new Ben_parent();// Prototype Inheritance 

var ben_son = new Ben_son();

console.log(ben_son instanceof Ben_son);//true

console.log(ben_son instanceof Ben_parent);//true

Example 3: Indicates that both the String object and the Date object are of type Object

The following code uses instanceof to prove that the String and Date objects are also of type Object.


var simpleStr = "This is a simple string"; 
var myString = new String();
var newStr  = new String("String created with constructor");
var myDate  = new Date();
var myObj   = {};

simpleStr instanceof String; // returns false,  Check the prototype chain and you will find  undefined
myString instanceof String; // returns true
newStr  instanceof String; // returns true
myString instanceof Object; // returns true

myObj instanceof Object;  // returns true, despite an undefined prototype
({}) instanceof Object;  // returns true,  Ditto 

myString instanceof Date;  // returns false

myDate instanceof Date;   // returns true
myDate instanceof Object;  // returns true
myDate instanceof String;  // returns false

Example 4: Demonstrating that mycar belongs to both Car and Object types

The code below creates a type Car and an object instance of that type, the mycar. instanceof operator, indicating that the mycar object belongs to both Car and Object types.


function Car(make, model, year) {
 this.make = make;
 this.model = model;
 this.year = year;
}
var mycar = new Car("Honda", "Accord", 1998);
var a = mycar instanceof Car;  //  Return  true
var b = mycar instanceof Object; //  Return  true


Related articles: