jquery static method type usage and source code analysis

Source: Internet
Author: User

The Jquery.type method is a tool method for detecting data types, summarizing the use of JS to provide us with the methods of monitoring data types before analyzing its usage;

One, typeof operator


Here is the test code

var data=[],a= ' 123 ', b=0,c=true, d={1:23},e=[123],f=function() {},g=null  New  Date ();d Ata.push (a,b,c,d,e,f,g,h,i,j,k);  for (var key=0;key<data.length;key++) {     console.log (Data[key]+ ' data type is ' +typeof Data[key]);}

In the above code, I try to enumerate the different data types and objects, the execution results are as follows:

//The 123 data type is string//0 of data type is number//the data type of true is Boolean//the data type of [Object Object] is Object//The 123 data type is Object//The data type of function () {} is function//the data type of undefined is undefined//the data type of [object Math] is Object//the data type of the/$.+^/is Object//Wed Jul 15:47:25 gmt+0800 (China Standard Time) data type is Object

We can see that typeof can detect 5 of the 6 basic types of JS, that is, string,boolean,number,undefined,object where null is attributed to the function of the Object to take out alone, Basically, you can accomplish the task, but that is not a further distinction for composite types, such as arrays or objects. At this point, you can use the other operator instanceof

Second, instanceof operator

Write the same test code

varData=[],a= ' 123 ', b=0,c=true, d={1:23},e=[123],f=function() {},g=NULL, h=undefined,i=math,j=/$.+^/,k=NewDate ();d Ata.push (a,b,c,d,e,f,g,h,i,j,k); Console.log (ainstanceofString); Console.log (binstanceofNumber ); Console.log (cinstanceofBoolean); Console.log (dinstanceofObject); Console.log (einstanceofArray); Console.log (finstanceofFunction); Console.log (JinstanceofRegExp); Console.log (kinstanceofDate);

The results of the operation in the browser are as follows:

// false // false // true // true // true // true // true

You can see that only the result of the composite type is true, and it must be guaranteed that the type is one by one corresponding, obviously this method can only do a test method exists, and can not be used when we do not know the specific data type of the time to make judgments, as a typeof of the auxiliary testing means

Third, constructor properties

Just write the test code first.

var data=[],a= ' 123 ', b=0,c=true, d={1:23},e=[123],f=function() {},g=null  Newfor (var key=0;key<data.length;key++) {       try{            Console.log (Data[key]+ ' test result is ' +data[key].constructor ');        } Catch (e) {        }    }

The results of the operation are as follows:

//123 test result is function String () {[native code]}//0 test result is function number () {[native code]}//true test result is function Boolean () {[native code]}//the test result of [object Object] is function object () {[native code]}//123 test result is function Array () {[native code]}//The test result of function () {} is function function () {[native code]}//the test result of [object Math] is function object () {[native code]}///$.+^/test result is function RegExp () {[native code]}Wed Jul 16:23:41 gmt+0800 (Chinese Standard Time) test result is function Date () {[native code]}

Where a null call is an error, so add a try statement, relative to this method can be very convenient to get its constructor, so it can be judged, unfortunately, this property is not a read-only property can be modified, Is there any other way to prevent problems such as being modified or related to object inheritance that can cause the program to fail to run, such as NULL, when it encounters some worthwhile error?

Iv. Methods of Object.prototype.toString

This method obtains the string representation of its constructor by invoking the ToString method of the data to be tested, and the test code is as follows:

    var data=[],a= ' 123 ', b=0,c=true, d={1:23},e=[123],f=function() {},g=null  New  Date ();    Data.push (a,b,c,d,e,f,g,h,i,j,k);      for (var key=0;key<data.length;key++) {            console.log (Data[key]+ ' test result is ' +  Object.prototype.toString.call (Data[key]));    }

The results of the operation are as follows:

//123 of the test result is [object String]//0 of the test result is [object number]//true detection result is [object Boolean]//the test result of [object Object] is [Object Object]//123 of the test result is [object Array]//The test result for function () {} is [object function]//null detection result is [object NULL]//The test result of Undefined is [object Undefined]//[Object Math] test result is [object Math]//The test result of/$.+^/is [object REGEXP]//Wed Jul 16:33:05 gmt+0800 (China Standard Time) Check/test result is [object Date]

It doesn't feel good to see the result! Not only can detect all data types, and the object subtype is also realistic, do not worry about the error, the reason can be achieved because all objects are based on object, in fact, Jqery is also taken this method, but is to do a further treatment let us look more cool!

Look at the results of using Jquery.type

    var data=[],a= ' 123 ', b=0,c=true, d={1:23},e=[123],f=function() {},g=null  New  Date ();    Data.push (a,b,c,d,e,f,g,h,i,j,k);      for (var key=0;key<data.length;key++) {            console.log (Data[key]+ ' test result is ' +$.type ( Data[key]));    }

Operation Result:

//the 123 test result is a string//0 of the test results are number//The test result is a Boolean//the test result of [object Object] is an object//the 123 test result is an array//The test result of function () {} is function//NULL detection result is NULL//Undefined's test results are undefined.//the test result of [object Math] is Object///$.+^/'s test results are regexp.//Wed Jul 16:44:25 gmt+0800 (China Standard Time) test result is date

OK, the result is impeccable, the following is attached to the source code:

function (obj) {        returnnull ?             String (obj):            | | "Object";    },

If it is undefined or null their data is tired type is itself, directly return the string form, if it is other data to execute the ToString method, the method is described earlier

toString = Object.prototype.toString,

The returned result is similar to the result of a previous test like [object Date], if it is not possible to return an object, the result is a Class2type key, and the following is the definition of Class2type:

// Populate the Class2type map function (i, name) {    "[object" + name + "]"] = name.tolowercase ();});

Okay, OK. The type method analysis is complete.

jquery static method type usage and source code analysis

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.