The difference between TypeOf and Instanceof in JS (2010-05-26-10:47:40

Source: Internet
Author: User

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


Typeoftypeof is a unary operation that can be any type before it is placed in an operand. 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")}, instead of using if (a) because if a does not exist (not declared) then an error will occur, for Array,null Such special objects use TypeOf to return object, which is the limitation of TypeOf. A small example on the Web: instanceofinstance: Instance, example 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 Var a=new array (); alert (a instanceof array); Returns True, and alert (a instanceof Object) also returns True because the Array is a subclass of Object. Again such as: function Test () {};var a=new test (), alert (a instanceof test) will return to talk about instanceof we want to insert a problem, is the function of arguments, we all may Arguments is considered to be an array, but if you use instaceof to test you will find that arguments is not an array object, although it looks like it. In addition: 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 '); ' n ' So, here's the instanceof test object refers to the JS syntax of object, not the DOM model objects. There are some differences in the use of typeof alert (typeof (Window)) will have an object

The difference between TypeOf and instanceof in

JS (2010-05-26 10:47:40

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.