typeof + Instanceof+tostring+constructor How to determine the JavaScript data type

Source: Internet
Author: User

First, typeof

The variables in JS are loosely typed (i.e., weakly typed) and can be used to hold any type of data.

typeof can be used to detect the data type of a given variable, the possible return value:
1. ' Undefined '---this value is undefined;
2. ' Boolean '---This value is a Boolean value;
3. ' String '---This value is a string;
4. ' Number '---this value is numeric;
5. ' Object '---This value is an object or null;
6. The ' function '---this value is a functional.

Test:
document.write ("typeof (1):" + typeof (1) + "<br>");d Ocument.write ("typeof (Nan):" + typeof (Nan) + "<br>"); document.write ("typeof (Number.min_value):" + typeof (Number.min_value) + "<br>") document.write ("typeof ( Infinity): "+ typeof (Infinity) +" <br> ") document.write (" typeof (\ "123\"): "+ typeof (" 123 ") +" <br> ") document.write ("typeof (True):" + typeof (True) + "<br>") document.write ("typeof (Window):" + typeof (Window) + "< Br> ") document.write (" typeof (document): "+ typeof (document) +" <br> ") document.write (" typeof (NULL): "+ typeof (null) + "<br>") document.write ("typeof (eval):" + typeof (eval) + "<br>") document.write ("typeof (Date):" + typeof (Date) + "<br>") document.write ("typeof (SSS):" + typeof (SSS) + "<br>") document.write ("typeof ( Undefined): "+ typeof (undefined) +" <br> ")
Test results:
typeof (1): number
typeof (NaN): number
typeof (Number.min_value): number
typeof (Infinity): number
typeof ("123"): string
typeof (True): Boolean
typeof (Window): Object
typeof (document): Object
typeof (NULL): Object
typeof (eval): function
typeof (Date): function
typeof (SSS): undefined
typeof (undefined): undefined
Resources
http://javaeyetodj.iteye.com/blog/1199125
Http://www.cnblogs.com/lidabo/archive/2011/12/29/2305770.html

Second, instanceof

In JavaScript, judging the type of a variable is often used with the typeof operator, a problem occurs when you store a value with a reference type when using the TypeOf operator, and it returns "Object" regardless of what type of object is referenced. This requires the use of instanceof to detect whether an object is an instance of another object.

Generally speaking, using instanceof is to determine whether an instance is of a certain type.
In addition, the heavier point is that instanceof can be used in an inheritance relationship to determine whether an instance belongs to its parent type. The above code determines the parent class in a hierarchy of inheritance relationships, and the instanceof operator is also applicable in multi-tier inheritance relationships.

Instanceof detects if an object A is an instance of another object B by looking at whether the object pointed to by prototype of Object B is on the [[prototype]] chain of object A. Returns true if it is, or false if it is not. There is a special case, however, when the prototype of object B is null, it will be an error (similar to a null pointer exception).

Test:

function Foo () {}foo.prototype = new Aoo ();//javascript prototype inherits var foo = new Foo (); Console.log (foo instanceof foo)//trueconso Le.log (foo instanceof Aoo)//trueconsole.log (Object instanceof object);//trueconsole.log (function instanceof function );//trueconsole.log (number instanceof number),//falseconsole.log (string instanceof String),//falseconsole.log ( function instanceof Object);//trueconsole.log (foo instanceof Function);//trueconsole.log (foo instanceof foo);//false
Resources
Http://www.studyofnet.com/news/175.html

Third, toString

Object.prototype.toString (). Call (param) Returns the type of Param (string, formatted as [object class]).

The ToString () method converts a logical value to a string and returns the result, with the syntax: Booleanobject.tostring (). Just now I said, JS objects are inherited object, these objects are custom to have functions or refactoring the object part of the function, and they are all the ToString () function is rewritten. So we can't just write param.prototype.toString () like in 1, so we're going to execute Param's own rewritten toString () function.

When the ToString method is called, the following procedure is performed:
1. Gets the value of the [[Class]] property of this object.
2. Calculated three string "[object", the first step of the operation result (1), and "]" after the connection of the new string.
3. Returns the result of the operation of the second step (2).
In ES3, the canonical document does not summarize the total number of [[Class]] intrinsic properties, but we can count on our own that there are 10 types of values for the native object's [[Class]] intrinsic properties. are: "Array", "Boolean", "Date", "Error "," Function "," Math "," number "," Object "," RegExp "," string ". So the output of Object.prototype.toString () is a string of this format [Object Array],[object Boolean].
So, ToString can judge: "Array", "Boolean", "Date", "Error", "Function", "Math", "number", "Object", "RegExp", "String"10 types of data above.


In ES5.1, there are changes to the definition of Object.prototype.toString methods and [[Class]] internal properties In addition to the more detailed specification writes, the Object.prototype.toString method is as follows:
When the ToString method is called, the following procedure is performed:
1 if the value of this is Undefined, "[Object Undefined]" is returned.
2 returns "[Object Null]" If the value of this is null.
3 Let o become the result of calling Toobject (this).
4 Let Class be the value of the internal property of O [[Class]].
5 returns a new string of three strings "[Object", Class, and "]" after the connection.
As you can see, more than ES3.1th, Step 2 is the new rule, which is special because "Undefined" and "Null" do not belong to the value of the [[Class]] property. By statistics, the types that can be returned are "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "number", "Object", "RegExp", "S Tring "2 more than the ES3 of the Arguments object is [[class]] became" Arguments ", not the previous" object ", there is more than the global object JSON, its [[Class] value is" JSON ".


Finally, we remind you that Object.prototype.toString (). Call (param) returns the [Object class] class with uppercase letters, such as JSON, which is even uppercase, so you can change to lowercase when you judge To prevent errors, Object.prototype.toString (). Call (param). toLowerCase ().

Test:

document.write ("{}.tostring.call (1):" + {}.tostring.call (1) + "<br>");d Ocument.write ("{}.tostring.call (NaN): "+ {}.tostring.call (NaN) +" <br> ");d Ocument.write (" {}.tostring.call (Number.min_value): "+ {}.tostring.call ( Number.min_value) + "<br>") document.write ("{}.tostring.call (Infinity):" + {}.tostring.call (Infinity) + "<br > ") document.write (" {}.tostring.call (\ "123\"): "+ {}.tostring.call (" 123 ") +" <br> ") document.write (" {}. Tostring.call (True): "+ {}.tostring.call (true) +" <br> ") document.write (" {}.tostring.call (window): "+ {}. Tostring.call (window) + "<br>") document.write ("{}.tostring.call (document):" + {}.tostring.call (document) + " <br> ") document.write (" {}.tostring.call (NULL): "+ {}.tostring.call (null) +" <br> ") document.write (" {} ". Tostring.call (eval): "+ {}.tostring.call (eval) +" <br> ") document.write (" {}.tostring.call (Date): "+ {}. Tostring.call (Date) + "<br>") document.write ("{}.tostring.call (undefined):" + {}.tostRing.call (undefined) + "<br>") document.write ("{}.tostring.call ({}):" + {}.tostring.call ({}) + "<br>") document.write ("{}.tostring.call (SSS):" + {}.tostring.call (SSS) + "<br>")

Test results:
{}.tostring.call (1): [Object number]
{}.tostring.call (NaN): [Object number]
{}.tostring.call (Number.min_value): [Object number]
{}.tostring.call (Infinity): [Object number]
{}.tostring.call ("123"): [Object String]
{}.tostring.call (True): [Object Boolean]
{}.tostring.call (window): [Object Global]
{}.tostring.call (document): [Object HTMLDocument]
{}.tostring.call (NULL): [Object null]
{}.tostring.call (eval): [Object Function]
{}.tostring.call (Date): [Object Function]
{}.tostring.call (undefined): [Objectundefined]
{}.tostring.call ({}): [Object object]

Resources:

Http://www.jb51.net/article/42864.htm

Iv. Constructor

Definition in the definition: The constructor property returns a reference to the array function that created this object.

Is the constructor that corresponds to the return object. It's not exactly the same as instanceof in terms of definition, but the effect is the same.
Note: The constructor error occurs when the class inherits
For example:
function A () {};function B () {}; A.prototype = new B (); A inherits from Bvar Aobj = new A (), alert (aobj.constructor = = = B)//-----------> true;alert (aobj.constructor = = = A)//---------- false;
The instanceof method does not have this problem, both direct and indirect inheritance of objects are reported true:
Alert (aobj instanceof B)//----------------> True;alert (aobj instanceof B)//----------------> true;
To get to the point, the problem of solving construtor is usually to constructor the object manually:
Aobj.constructor = A; Assign your own class to the object's Constructor property alert (Aobj.constructor = = = A)//-----------> true;alert (aobj.constructor = = B)//------ -----> false; The base class does not report true;
Test:
Console.log ([].constructor = = <strong>Array</strong>); Trueconsole.log ({}.constructor = = <strong>Object</strong>); Trueconsole.log ("string". Constructor = = <strong>String</strong>); Trueconsole.log ((123). constructor = = <strong>Number</strong>); Trueconsole.log (True.constructor = = <strong>Boolean</strong>); Trueconsole.log (New Date ()). constructor = = <strong>Date</strong>);//true

Reference: http://blog.sina.com.cn/s/blog_51048da70101grz6.html

V. Type judgments in jquery

Type () method

Type:function (obj) {    if (obj = = null) {        return String (obj);    }    return typeof obj = = = "Object" | | typeof obj = = = "function"?        class2type[Core_tostring.call (obj)] | | "Object":        typeof obj;},


typeof + Instanceof+tostring+constructor How to determine the JavaScript data type

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.