An example of how to use JavaScript instanceof

  • 2020-03-26 21:32:36
  • OfStack

In JavaScript, the typeof operator is used to determine the typeof a variable, and there is a problem with using the typeof operator to store values in reference types, which return "object" regardless of the typeof object being referenced. This requires instanceof to check whether an object is an instanceof another object.

In general, using instanceof is about determining whether an instance belongs to a type.
Further, instanceof can be used in inheritance relationships to determine whether an instance belongs to its parent type.
 
//Function Aoo(){} function Aoo(){}
function Foo(){} 
Foo.prototype = new Aoo();//JavaScript prototype inheritance
var foo = new Foo(); 
console.log(foo instanceof Foo)//true 
console.log(foo instanceof Aoo)//true 

The above code is used to determine the parent class in a hierarchical inheritance relationship, in which the instanceof operator also applies.

Complex use of instanceof
 
function Cat(){} 
Cat.prototype = {} 

function Dog(){} 
Dog.prototype ={} 

var dog1 = new Dog(); 
alert(dog1 instanceof Dog);//true 
alert(dog1 instanceof Object);//true 

Dog.prototype = Cat.prototype; 
alert(dog1 instanceof Dog);//false 
alert(dog1 instanceof Cat);//false 
alert(dog1 instanceof Object);//true; 

var dog2= new Dog(); 
alert(dog2 instanceof Dog);//true 
alert(dog2 instanceof Cat);//true 
alert(dog2 instanceof Object);//true 

Dog.prototype = null; 
var dog3 = new Dog(); 
alert(dog3 instanceof Cat);//false 
alert(dog3 instanceof Object);//true 
alert(dog3 instanceof Dog);//error 

To fundamentally understand the mysteries of instanceof, you need to start with two things: 1. How the operator is defined in the language specification. 2. JavaScript prototype inheritance machine. You are interested in can go to see the relevant materials.

Related articles: