In JavaScript, to judge the type of a variable to try the typeof operator, it is a problem to store a value using a reference type when using the TypeOf operator, regardless of what type of object is referenced, it returns "Object". This requires the use of instanceof to detect an instance of an object that is not another object.
Generally speaking, using instanceof is to judge whether an instance is of a certain type.
In addition, the heavier point is that instanceof can be used in an inheritance relationship to determine whether an instance belongs to its parent type.
Copy Code code as follows:
Determine if Foo is an instance of the Foo class and whether it is an instance function Aoo () {} of its parent type
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 a judgment of the parent class in a layer of inheritance, in which the instanceof operator is also applicable.
instanceof Complex usage
Copy Code code as follows:
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 aspects: 1, how the operator is defined in the language specification. 2,javascript prototype successor machine. People interested can go to see the relevant information.