Typeof + instanceof + toString + constructor: How does one determine the javascript data type? typeofinstanceof

Source: Internet
Author: User

Typeof + instanceof + toString + constructor: How does one determine the javascript data type? typeofinstanceof
I. typeof

Variables in JS are loose (weak type) and can be used to save any type of data.

Typeof can be used to detect the Data Type of a given variable. Possible return values:
1. 'undefined' --- the value is undefined;
2. 'boolean' --- the value is a boolean value;
3. 'string' --- the value is a string;
4. 'number' --- the value is a numerical value;
5. 'object' --- the value is an object or null;
6. 'function' --- the value is a function.

Test:
document.write("typeof(1): " + typeof(1) + "<br>");document.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
References
Http://javaeyetodj.iteye.com/blog/1199125
Http://www.cnblogs.com/lidabo/archive/2011/12/29/2305770.html

Ii. instanceof

In JavaScript, the typeof operator is often used to judge the type of a variable. When the typeof operator is used, the storage value of the reference type may become a problem, no matter what type of object is referenced, it returns "object ". This requires the use of instanceof to detect whether an object is an instance of another object.

Generally Instanceof is used to determine whether an instance belongs to a certain type.
In addition, the more important thing is that instanceof can be used in the inheritance relationship to determine whether an instance belongs to its parent type. The above code judges the parent class in an inheritance relationship. In multi-level inheritance relationships, the instanceof operator also applies.

How instanceof checks whether object A is an instance of another object B is: Check whether the prototype of object B points to the object in the [[prototype] chain of object. If yes, true is returned. If not, false is returned. However, when prototype of object B is null, an error is returned (similar to a null pointer exception ).

Test:

Function Foo () {} Foo. prototype = new Aoo (); // The JavaScript prototype inherits var foo = new Foo (); console. log (foo instanceof Foo) // trueconsole. 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
References
Http://www.studyofnet.com/news/175.html

3. toString

Object. prototype. toString (). call (param) returns the param type (string, in the format of [object class]).

The toString () method converts a logical value to a string and returns the result. Syntax: booleanObject. toString (). As I said just now, all objects in js are inherited objects. All these objects have custom functions or some functions that reconstruct objects, and they all have toString () the function is rewritten. Therefore, we cannot directly write param. prototype. toString () in 1, so we can execute the toString () function after param overwrites itself.

When the toString method is called, the following steps are performed:
1. Obtain the value of the [[Class] attribute of this object.
2. Calculate the three strings "[object", Result (1) of the first step, and new string after.
3. Return the Result of the second step (2 ).
In ES3, the specification document does not summarize the Internal Attributes of [[class]. However, we can make statistics by ourselves, there are 10 types of native [[class] internal attribute values. they are: "Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object", "RegExp ", "String ". so Object. prototype. the output result of toString () is the string [object Array], [object Boolean] in this format.
Therefore, toString can be used to determine: "Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object", "RegExp", "String"The above 10 data types.


In ES5.1, Object. prototype. the toString method and the definition of the [[class] internal attribute also have some changes, Object. prototype. the toString method specifications are as follows:
When the toString method is called, the following steps are performed:
1. If the value of this is undefined, "[object Undefined]" is returned.
2. If the value of this is null, "[object Null]" is returned.
3. Make O the result of calling ToObject (this.
4. Make the class the value of the internal attribute [[Class] of O.
5. Return the new string after the three strings "[object", class, and "]" are connected.
It can be seen that step 1, step 3, step 1, and step 2 are new rules, which are special because "Undefined" and "Null" do not belong to the value of the [[class] attribute. According to statistics, the return types include "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math ", "Number", "Object", "RegExp", "String" has two more types than ES3: [[class] of the arguments Object to "Arguments ", instead of the previous "Object", there are multiple global Object JSON whose [[class] value is "JSON ".
]

Finally, I would like to remind you that Object. prototype. toString (). in the [object class] returned by call (param), the first letter of the class is in upper case, such as JSON, and even in upper case. Therefore, you can convert the class to lower case when making a decision to avoid errors. prototype. toString (). call (param ). toLowerCase.

Test:

document.write("{}.toString.call(1): " + {}.toString.call(1) + "<br>");document.write("{}.toString.call(NaN): " + {}.toString.call(NaN) + "<br>");document.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): [objectNumber]
{}. ToString. call (NaN): [objectNumber]
{}. ToString. call (Number. MIN_VALUE): [objectNumber]
{}. ToString. call (Infinity): [objectNumber]
{}. ToString. call ("123"): [objectString]
{}. ToString. call (true): [objectBoolean]
{}. ToString. call (window): [objectGlobal]
{}. ToString. call (document): [objectHTMLDocument]
{}. ToString. call (null): [objectNull]
{}. ToString. call (eval): [objectFunction]
{}. ToString. call (Date): [objectFunction]
{}. ToString. call (undefined): [objectUndefined]
{}. ToString. call ({}): [objectObject]

References:

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

Iv. constructor

Definition in W3C definition: the constructor attribute returns a reference to the array function that creates this object.

Returns the constructor corresponding to the object. In terms of definition, it is not consistent with instanceof, but the effect is the same.
Note: constructor errors during class inheritance
For example:
Function A () {}; function B () {};. prototype = new B (); // A inherits from Bvar aObj = new A (); alert (aobj. constructor = B) // -----------> true; alert (aobj. constructor === A) // -----------> false;
This problem does not occur in the instanceof method, and true is reported for objects directly inherited or indirectly inherited:
alert(aobj instanceof B) //----------------> true;alert(aobj instanceof B) //----------------> true;
To put it bluntly, the problem of solving the construtor is usually to manually direct the constructor of the object to itself:
Aobj. constructor = A; // assign your class to the constructor attribute alert (aobj. constructor = A) // -----------> true; alert (aobj. constructor = B) // -----------> false; // The base class will 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

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

V. Type determination 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;},



Javascript instanceof Problems

Str = '20140901 ';
Str is a string type.
But it is not an object.
Since it is not an object, you instanceof anything cannot be true.
Unless you declare
Var str = new String ('20140901 ')

Javascript will also automatically disassemble the box.
Str = '000000'
Str is the basic data type.
However, when you call the str. substring method.
The javascript interpreter temporarily packs str into a String object and releases it.
So str is not an object, but sometimes it is also an object. This is confusing.

Instanceof operator usage in JavaScript

Instanceof is used to determine whether an object is of a certain data type or whether a variable is an instance of an object. A boolean type is returned.
The syntax is o instanceof.
The following is a comprehensive example:

1 <script type = "text/javascript">
2 <! -
3 alert ("typeof (1):" + typeof (1); // number
4 alert ("typeof (\" abc \ "):" + typeof ("abc"); // string
5 alert ("typeof (true):" + typeof (true); // boolean
6 alert ("typeof (2009-2-4):" + typeof (2009-2-4); // number
7 alert ("typeof (\" 2009-2-4 \ "):" + typeof ("2009-2-4 2-4"); // string
8 alert ("typeof (m):" + typeof (m); // undefined
9 var d = new Date ();
10 alert ("typeof (d):" + typeof (d); // object
11 function Person (){};
12 alert ("typeof (Person):" + typeof (Person); // function
13 var a = new Array ();
14 alert ("typeof (a):" + typeof (a); // object
15 alert ("a instanceof Array:" + (a instanceof Array ));
16 var h = new Person ();
17 var o = {};
18 alert ("h instanceof Person:" + (h instanceof Person); // true
19 alert ("h instanceof Object:" + (h instanceof Object); // true
20 alert ("o instanceof Object:" + (o instanceof Object); // true
21 alert (typeof (h); // object
22 //->
23 </script>

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.