JavaScript type detection: typeof and instanceof defects and optimization _ javascript skills

Source: Internet
Author: User
In javascript, typeof and instanceof are two common methods for judging data types, the purpose of this article is to analyze the shortcomings of the two methods and propose an optimization solution. In javascript, typeof and instanceof are two common methods for judging data types, this article aims to analyze the shortcomings of these two methods and propose an optimization solution.

Typeof

--------------------------------------------------------------------------------

Typeof returns a string of the expression data type. The returned result is of the basic data type in javascript, including number, boolean, string, object, undefined, and function.

typeof 100; //numbertypeof (1==1); //booleantypeof 'onepixel'; //stringtypeof {} ; //objecttypeof onepixel; // undefinedtypeof parseInt; // functiontypeof [];//objecttypeof new Date(); //object 

We can see that typeof can accurately determine basic data types other than objects, but cannot distinguish specific types of object types, such as Array, Date, and custom classes.

Instanceof

--------------------------------------------------------------------------------

Instanceof is an instance object used to determine whether A is B. The expression is A instanceof B. If A is a B instance, true is returned. Otherwise, false is returned. Here, we need to pay special attention to the following: instanceof detects the prototype and how it detects it. We use a piece of pseudo code to simulate its internal execution process:

Instanceof (A, B) = {var L =. _ proto __; var R = B. prototype; if (L = R) {// The internal attribute of A _ proto _ points to the prototype object of B return true;} return false ;}

From the above process, we can see that when _ proto _ of A points to prototype of B, it is considered that A is the Instance Object of B. Let's look at several examples:

[] instanceof Array; //true{} instanceof Object;//truenew Date() instanceof Date;//truefunction Person(){};new Person() instanceof Person;[] instanceof Object; //truenew Date() instanceof Object;//trunew Person instanceof Object;//true 

In the above example, we found that although instanceof can correctly judge that [] is an Array instance Object, it cannot identify that [] is not an Object instance Object. Why, this also needs to start with the prototype chain of javascript. First, we will analyze the relationship among [], Array, and Object. From instanceof, we can judge that []. _ proto _-> Array. prototype, while Array. prototype. _ proto _ points to the Object. prototype, Object. prototype. _ proto _ points to null, marking the end of the prototype chain. (Ps: For details about the JS prototype chain, refer to the javascript prototype and prototype chain.) Therefore, [], Array, and Object form a prototype chain:

From the prototype chain, we can see that [] _ proto _ finally points to the Object. prototype, similar to new Date () and new Person (), also forms such a prototype chain. Therefore, we cannot use instanceof to completely accurately determine the specific data type of the object class.

Optimization Scheme

--------------------------------------------------------------------------------

When reading the jQuery source code, we found a better solution. Because there are mutual calls between source codes, it is not easy to read and understand. Therefore, the Code is as follows:

(function(){var class2type = {};var typeList = "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " );typeList.eachEach(function(item){class2type[ "[object " + item + "]" ] = item.toLowerCase();}return {getObjType:function(obj) {if ( obj == null ) {return obj + "";}if(typeof obj === "object" || typeof obj === "function"){class2type[ toString.call( obj ) ] || "object"}else {return typeof obj;}}}})()

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

Typeof

Typeof is a one-dimensional operation. Before a single operation, the operation can be of any type.

The return value is a string that represents the type of the number of operations. Typeof generally only returns the following results:

Number, boolean, string, function, object, undefined. We can use typeof to obtain whether a variable exists, such as if (typeof! = "Undefined") {alert ("OK")}, instead of using if (a) because if a does not exist (not declared), an error will occur. For Array, null and other special objects use typeof to return all objects, which is the limitation of typeof.

A small example on the Internet:

 
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.