JavaScript type detection: typeof and instanceof defects and optimization, typeofinstanceof

Source: Internet
Author: User

JavaScript type detection: typeof and instanceof defects and optimization, typeofinstanceof

In javascript, typeof and instanceof are two common methods for judging data types. The purpose of this article is to analyze the shortcomings of these two methods and propose optimization solutions.

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:

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

Instanceof

Instance: instance, for example

A instanceof B? Alert ("true"): alert ("false"); // is a B instance? True: false

Instanceof is an instance used to determine whether a variable is an Object, such as var a = new Array (); alert (a instanceof Array); true is returned, and alert (a instanceof Object) true is also returned because Array is a subclass of the object. For example, function test () {}; var a = new test (); alert (a instanceof test) will return
When talking about instanceof, We need to insert another question: function arguments. We may all think that arguments is an Array. However, if we use instaceof to test, we will find that arguments is not an Array object, although it looks very similar.

In addition:

Test var a = new Array (); if (a instanceof Object) alert ('y'); else alert ('n ');

Get 'y'

However, if (window instanceof Object) alert ('y'); else alert ('n ');

'N'

Therefore, the instanceof object here refers to the object in js syntax, not the dom model object.

There are some differences when typeof is used.

Alert (typeof (window) will get the object

Do you know whether the type of function parameter in JavaScript is typeof or instanceof?

Typeof can only determine the existing js types, such as function, object, and number.

Instanceof can be used to determine which function of the object is instantiated, for example:

var a=function(x){};var b=function(x){};var c=new a(1);var d=new a(2);

C instanceof a is true, and d instanceof B is false.

The results of using typeof c and typeof d are all objects.

To determine the function parameter type, you need to select which one to use based on your needs.

Articles you may be interested in:
  • Use of javascript instanceof and typeof
  • Differences between javascript instanceof and typeof
  • Introduction to typeof and instanceof in javascript
  • Javascript typeof and instanceof Operators
  • Summary of differences between typeof and instanceof in JS
  • The usage and difference of the instanceof and typeof operators in JavaScript
  • On instanceof and typeof in javascript
  • My in-depth understanding of typeof and instanceof in JavaScript

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.