The difference between Javascript typeof and Instanceof _ Basics

Source: Internet
Author: User

In JavaScript, typeof and instanceof are often used to determine whether a variable is empty or what type it is. But there is a difference between them:

typeof

TypeOf is a unary operation, which can be any type of operation before it is placed in one op-count.

The return value is a string that describes the type of the operand. typeof generally can only return the following results:
number,boolean,string,function,object,undefined. We can use TypeOf to get the existence of a variable, such as if (typeof a!= "undefined") {alert ("OK")}, and not to use if (a) because if a does not exist (not declared) there will be an error, for the Array,null Such special objects use TypeOf to return object, which is the limitation of TypeOf.

instanceof

Instance: examples, examples

A instanceof B?alert ("true"): Alert ("false"); A is an example of B? True: false

Instanceof is used to determine whether a variable is an instance of an object, such as the Var a=new array (); alert (a instanceof array); Returns True, while alert (a Instanceof object) returns True, because the Array is a subclass of Object. Another example: function Test () {};var a=new test (); alert (a instanceof test) returns

When it comes to instanceof, we're going to insert one more question, which is the arguments of the function, and we all probably think that arguments is an array, but if you use instaceof to test, you'll find that arguments is not an array object, though it looks like it.

Other than that:

Test var a=new Array (); if (a instanceof Object) alert (' Y '); else alert (' N ');

Get ' Y '

But if (window instanceof Object) alert (' Y '); else alert (' N ');

Get ' N '

So, the object of the instanceof test here refers to the object in the JS syntax, not the DOM model object.

There are some differences between using typeof

Alert (typeof (Window)) Gets object

Thank you for reading, I hope to help you, thank you for your support for this site!

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.