Several methods of judging JS data type

Source: Internet
Author: User

Translated from http://www.cnblogs.com/onepixel/p/5126046.html!

When it comes to data types, let's talk about several common data types in javascript:

base type : String,number,boolean

Special type : Undefined,null

reference type : Object,function,function,array,regexp,date,...

Most of the time we need to determine the data type of the variable to do the next step, below we introduce 4 common methods:

typeof‘‘;//string is validtypeof1;//Number is validtypeof true;//Boolean validtypeofUndefined//undefined effectivetypeof NULL;//Invalid objecttypeof[] ;//Invalid objecttypeof NewFunction ();//function Validtypeof NewDate ();//Invalid objecttypeof NewRegExp ();//Invalid object

typeof can make accurate judgments about the JS base data type, and the return of the reference type is basically object, but it is not wrong to return object, because the prototype chain of all objects ultimately points to object,object as the ' ancestor ' of all objects. But when we need to know the specific type of an object, typeof seems to be a little overwhelmed.

2, instanceof

Instanceof is an instance pair used to determine if A is B, and the expression is: a instanceof B, if a is an instance of B, returns True, otherwise false. In particular, it is important to note thatInstanceof detects prototypes , and we use a pseudo-code to simulate their internal execution:

instanceof (A, b) = {    var L = a.__proto__;     var R = b.prototype;     if (L = = R)        {//A internal property __proto__ the prototype object pointing to B        returntrue ;    }     return false ;}

As can be seen from the above process, when A's __proto__ points to the prototype of B, we think that a is an example of B, and we'll look at a few more examples:

[]instanceofArray;//true{}instanceofObject;//trueNewDate ()instanceofDate;//true functionPerson () {};NewPerson ()instanceofPerson ; [] instanceofObject;//trueNewDate ()instanceofObject;//trueNewPersoninstanceofObject;//true

We find that although instanceof can tell that [] is an instance of an array, it thinks [] is also an instance of object, why? Let's analyze the relationship between [], Array, Object three: from instanceof can judge [].__proto__ Point Array.prototype, and array.prototype.__proto__ Pointed again to the object.prototype,object.prototype.__proto__ pointing to null, marking the end of the prototype chain. Thus, [], Array, and object form a prototype chain as shown:

From the prototype chain can be seen, [] the __proto__ directly point to array.prototype, indirect point to object.prototype, so according to the rules of instanceof, [] is an instance of object. Of course, a similar new Date () and new person () will also form a prototype chain, so instanceof can only be used to determine whether two objects are part of the prototype chain, not the exact type of the object.

3, constructor

When a function f is defined, the JS engine adds a prototype prototype to F, and then adds a constructor property on prototype and points it to the reference of F. As shown below:

When the var f = new F () is executed, F is considered a constructor and F is an instance object of F, at which point the constructor on the F prototype is passed to F, so f.constructor = = f

As you can see, JS defines constructor on the prototype of function F, when F is used as a constructor to create an object, the new object created is marked for the "F" type, so that the new object has a surname and can be traced.

In the same vein, the data types in JS follow this rule:

Detail questions:

    • Null and undefined are invalid objects, so there is no constructor, and these two types of data need to be judged by TypeOf.
    • JS Object constructor is not stable, this is mainly embodied in the custom object, when the developer rewrite prototype, the original constructor will be lost, constructor will default to object

Why did you become an object?

Prototype is re-assigned a {}, {} is the literal of the new object (), so new object () passes the constructor on the object prototype to {}, which is the object itself.

Therefore, in order to standardize, it is generally necessary to re-assign the constructor when overriding the object's prototype to ensure that the type of the instance object is not overwritten.

4, Object.prototype.toString

ToString is a method on object prototype objects that returns the specific type of its caller by default, and more strictly, the object type that the ToString runtime this refers to, and returns the type format of [object,xxx],xxx is the specific data type, These include: String,number,boolean,undefined,null,function,date,array,regexp,error,htmldocument,... Basically, all object types can be obtained by this method.

Object.prototype.toString.call (");//[Object String]Object.prototype.toString.call (1);//[Object number]Object.prototype.toString.call (true) ;//[Object Boolean]Object.prototype.toString.call (undefined);//[Object Undefined]Object.prototype.toString.call (NULL) ;//[Object Null]Object.prototype.toString.call (NewFunction ());//[Object Function]Object.prototype.toString.call (NewDate ());//[Object Date]Object.prototype.toString.call ([]);//[Object Array]Object.prototype.toString.call (NewREGEXP ());//[Object RegExp]Object.prototype.toString.call (NewError ());//[Object Error]Object.prototype.toString.call (document);//[Object HTMLDocument]Object.prototype.toString.call (window);//[Object Global] window is a reference to global object globals

It is important to note that it must be obtained through Object.prototype.toString.call , not directly to new Date (). ToString (), from the point of view of the prototype chain, the prototype chain of all objects eventually points to object, According to the JS variable lookup rule, other objects should also have direct access to the ToString method of object, and in fact, most of the objects implement their own ToString method, which may cause the object's ToString to be terminated to find, Therefore, call is used to enforce the ToString method of object.

Several methods of judging JS data type

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.