How to use JavaScript instanceof Sample Introduction _ Basics

Source: Internet
Author: User
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.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.