The difference between JavaScript instanceof and typeof

Source: Internet
Author: User

Referenced from: http://www.cnblogs.com/eoiioe/archive/2008/12/31/1366081.html

Both instanceof and typeof can be used to determine whether a variable is empty or what type of variable it is.

typeof is used to get the type of a variable, 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") {}, instead of using if (a) because if a does not exist (not declared) then an error occurs, for array, Special objects such as null use TypeOf to return object, which is the limitation of typeof.

choose to use instanceof if we want to get an object that is an array, or whether a variable is an instance of an object.

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) returns True.

When it comes to instanceof we need to insert one more question, that is, the function of arguments, we all may think arguments is an array, But if you use instaceof to test you will find that arguments is not an array object, though it looks like.

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 in the instanceof test here refers to the object in the js syntax, not the Dom model objects.

There are some differences between using typeof
Alert (typeof (window) will have an object

The difference between JavaScript instanceof and typeof

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.