In JavaScript, the typeof operator is often used to determine the type of a variable. When using the typeof operator, a problem arises when using a reference type to store values. No matter what type of object is referenced, it returns "object". This requires instanceof to detect whether an object is an instance of another object.
Generally speaking, using instanceof is to determine whether an instance belongs to a certain type.
In addition, a more important point is that instanceof can be used in inheritance relationships to determine whether an instance belongs to its parent type.
// Determine whether foo is an instance of the Foo class, and Whether it is an instance of its parent type function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo();//JavaScript prototypal inheritance
var foo = new Foo();
console.log(foo instanceof Foo)//true
console.log(foo instanceof Aoo)//true
The above code determines the level of inheritance relationship Parent class, in multi-level inheritance relationships, the instanceof operator is also applicable.
Instanceof complex usage
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 mystery of instanceof, you need to start from two aspects: 1. How this operator is defined in the language specification. 2. JavaScript prototype inheritance machine. If you are interested, you can check the relevant information.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn