The typeof and 0bject.prototype.tostring explanation of the methods of judging the types of data in JS

Source: Internet
Author: User

Reproduced from the "Script House", the original link: http://www.jb51.net/article/42864.htm reminds you, Object.prototype.toString (). Call (param) returns the [Object Class] class initials are uppercase, such as JSON, which is even uppercase, so you can judge the time to convert to lowercase, in case of error

1, typeof (Param) Returns the type of Param (string)

This method is the definition of JS in the global method, but also the compiler is the most common method, the advantage is to use simple, good remember, the disadvantage is not very good to judge object, NULL, array, regexp and custom objects.

Example code:

Copy CodeThe code is as follows:
var str= ' str ';
var arr=[' 1 ', ' 2 '];
var num=1;
var bool=true;
var obj={name: ' Test '};
var nullobj=null;
var undefinedobj=undefined;
var reg=/reg/;

function fn () {
Alert (' This is a function ');
}

function User (name) {
This.name=name;
}
var user=new user (' user ');

Console.log (typeof (str));
Console.log (typeof (arr));
Console.log (typeof (Num));
Console.log (typeof (BOOL));
Console.log (typeof (obj));
Console.log (typeof (Nullobj));
Console.log (typeof (Undefinedobj));
Console.log (typeof (Reg));
Console.log (typeof (FN));
Console.log (typeof (user));


The result is:
Copy CodeThe code is as follows:
String
Object
Number
Boolean
Object
Object
Undefined
Object
function
Object
2, Object.prototype.toString (). Call (param) Returns the type of param (string, format [Object class])

This method supports most types of judgments, and this method is used to determine the type of jquery encapsulation. Maybe some people seem a little confused, let me break it down for you.

1) call (param) function

A.fun (). Call (b) means, in JS, that the object B replaces a, and then executes the fun function of a, writing an example:

Copy CodeThe code is as follows:
function Class1 ()
{
THIS.name = "Class1";

This.shownam = function ()
{
alert (this.name);
}
}

function Class2 ()
{
THIS.name = "Class2";
}

var C1 = new Class1 ();
var C2 = new Class2 ();

C1.showNam.call (C2);


Running the result, the output is class2, not Class1, which is equivalent to method inheritance.
So, Object.prototype.toString (). Call (param) means actually, param.prototype.toString (), So why don't we just write param.prototype.toString (), but use call () to wrap around it, and then look at the second.

2) Object.prototype.toString ()

What's an object? , Script56.chm (m$ official tutorial) said: Obect provides all the functionality common to JScript objects, in fact, object is the ancestor of all JS objects, is a concept, JS all objects is an instance of object, Then different objects rewrite their own independent methods. And prototype, there is no need to pursue too deep, it is to return a reference to a prototype, you can dynamically add methods and properties to the prototype
A small example

Copy CodeThe code is as follows:
function Class () {
THIS.name = "Class";
This.showname = function () {
alert (this.name);
}
}
var obj = new Class ();
Obj.showname ();
Class.prototype.showNameContact = function () {
Alert ("Prototype test" +this.name);
}
Obj.shownamecontact ();
Then the class and prototype test class will be output separately, the constructor class () is not defined shownamecontact function, and through prototype we can add functions to the object prototype dynamically, In the new example, you will naturally have it. So Object.prototype.toString () means executing the ToString method in the ancestor of object.

So what does ToString () do? The ToString () function is defined in many JS manuals:
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 not think of 1 directly write param.prototype.toString () so that the implementation is param own rewrite after the toString () function.

Well, to the critical moment, what does toString () do, and what does it do?

In ES3, the specification of the Object.prototype.toString method is as follows:

Object.prototype.toString ()

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].

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:

Object.prototype.toString ()
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 ().

Articles you may be interested in:
    • JavaScript typeof usage and typeof operator introduction [detail]
    • Javascript typeof Usage
    • JavaScript isprototypeof and hasOwnProperty use differences
    • The difference between JavaScript instanceof,typeof
    • JS judge undefined variable type using typeof
    • A summary of the difference between TypeOf and instanceof in JS
    • A detailed analysis of the usage and difference of instanceof and typeof operators in JavaScript
    • Summary of usage of typeof in JS
    • Summary of typeof usage in JavaScript

The typeof and 0bject.prototype.tostring explanation of the methods of judging the types of data in JS

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.