jquery static method Type/noconflict usage and source analysis

Source: Internet
Author: User
Tags constructor custom name

Jquery.type usage and source analysis

Jquery.type method is a tool to detect data types, before analyzing its usage, we summarize the methods that JS provides for us to monitor data types.

First, typeof operator

Here is the test code

var data=[],a= ' 123 ', b=0,c=true,d={1:23},e=[123],f=function () {},g=null,h=undefined,i=math,j=/$.+^/,k= 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]+ ' data type is ' +typeof Data[key]);

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

The data type of 123 is string
0 of the data type is number
The data type of TRUE is a Boolean
The data type of [object] is Object
The data type of 123 is Object
The data type of function () {} is a function
The undefined data type is undefined
The data type of [object Math] is Object
The/$.+^/data type is Object
Wed June 2015 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 Object, and the function is taken out alone, The task is basically complete, but that's not a further distinction for composite types, like arrays or objects? This time we can use another operator to instanceof the

Second, instanceof operator

Write a piece of the same test code

var data=[],a= ' 123 ', b=0,c=true,d={1:23},e=[123],f=function () {},g=null,h=undefined,i=math,j=/$.+^/,k= new Date ();
Data.push (A,B,C,D,E,F,G,H,I,J,K);
Console.log (a instanceof String);
Console.log (b instanceof number);
Console.log (c instanceof Boolean);
Console.log (d instanceof Object);
Console.log (e instanceof Array);
Console.log (f instanceof Function);
Console.log (J instanceof RegExp);
Console.log (k instanceof Date);

The results of running in the browser are as follows:


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 one test method exists, and not when we do not know the specific data type of the time to make judgments, can be used as an auxiliary test typeof

third, constructor properties

Write the same test code first

var data=[],a= ' 123 ', b=0,c=true,d={1:23},e=[123],f=function () {},g=null,h=undefined,i=math,j=/$.+^/,k= new Date ();
Data.push (A,B,C,D,E,F,G,H,I,J,K);
for (Var key=0;key<data.length;key++) {
The test result of Console.log (data[key]+ ') is ' +data[key].constructor ';
}catch (e) {


The results of the operation are as follows:

The test result for 123 is function String () {[native code]}

The test result for 0 is function number () {[native code]}

The detection result for true is function Boolean () {[native code]}

The test result for [object] is function object () {[native code]}

The test result for 123 is function Array () {[native code]}

The detection result for function () {} is a function function () {[native code]}

The detection result of [object Math] is a function object () {[native code]}

$.+^/'s detection result is function RegExp () {[native code]}
Wed June 2015 16:23:41 gmt+0800 (China Standard Time) detection result is function Date () {[native code]}

Where the null call is an error, so the try statement is added, which is relatively convenient to obtain its constructor, so that it can be judged, unfortunately this property is not a read-only property can be modified, Is there any other way to do this when it is modified or when it comes to problems such as object inheritance that can cause programs not to run, such as NULL, when there are some worthwhile errors?

Four, Object.prototype.toString method

The method obtains a string representation of its constructor by calling the ToString method of the data to be tested, as follows:

var data=[],a= ' 123 ', b=0,c=true,d={1:23},e=[123],f=function () {},g=null,h=undefined,i=math,j=/$.+^/,k= new Date ();
Data.push (A,B,C,D,E,F,G,H,I,J,K);
for (Var key=0;key<data.length;key++) {
The test result of Console.log (data[key]+ ') 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]

The test result for true is [object Boolean]

The result of [object] detection is [object]

123 of the test result is [object Array]

The detection result for function () {} is [object Function]

The result of null detection is [object Null]

Undefined's test result is [object Undefined]

The test result of [object math] is [object Math]

$.+^/'s test result is [object REGEXP]

Wed June 2015 16:33:05 gmt+0800 (China Standard Time) inspection/test results are [object Date]

Does it feel good to see the result? Not only can you detect all data types, and the object subtype also reality out, do not worry about the error, the reason can be achieved because all objects are based on the object, in fact, Jqery is also adopted this method, but it is done further processing let us look more fun!

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,h=undefined,i=math,j=/$.+^/,k= new Date ();
Data.push (A,B,C,D,E,F,G,H,I,J,K);
for (Var key=0;key<data.length;key++) {
The test result of Console.log (data[key]+ ') is ' +$.type (Data[key]);

Run Result:

123 of the test result is string

0 of the test results are number

The test results are Boolean

The test result of [object] is Object

123 of the test results are array

The detection result for function () {} is a 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 June 2015 16:44:25 gmt+0800 (China Standard Time) test results are date

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

Type:function (obj) {
return obj = null?
String (obj):
class2type[Tostring.call (obj)] | | "Object";

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

toString = Object.prototype.toString,

The result returned is similar to the result of the previous test, such as [object Date], which returns object if it cannot be fetched, the result is a Class2type key, and the following is the definition of Class2type:

Populate the Class2type map
Jquery.each ("Boolean number String Function Array Date RegExp Object". Split (""), Function (i, name) {
class2type["[Object" + name + "]"] = Name.tolowercase ();

All right, the type method is finished.

the use of jquery.noconflict and source analysis

The so-called static method is the public method of jquery itself, does not need to be instantiated to invoke, commonly referred to as tool methods, the following first to list the use of the Jquery.noconflict method:

The Noconflict () method lets the JQuery control of the variable $.

This method frees up the control of the $ variable in jQuery.

The method can also be used to prescribe a new custom name for the jQuery variable.

var jq=$.noconflict ();

Here's a test:

<script src= ' jquery-1.7.1.js ' ></script>
Alert ($); function () {...}

Results after calling the Noconflict method:

<script src= ' jquery-1.7.1.js ' ></script>
$.noconflict ();
Alert ($); undefinded

At this time $ is no longer the alias of jquery, plus the following parameters

<script src= ' jquery-1.7.1.js ' ></script>
$.noconflict (TRUE);
alert (jQuery); Undefined

So jquery is released. Many JavaScript libraries use $ as a function or variable name, as is jquery. In jquery, $ is just the alias of jquery, so even if you don't use $, you can guarantee all of the functionality. If we need to use another JavaScript library outside of JQuery, we can return control to the library by calling $.noconflict ():

<script type= "Text/javascript" src= "Other_lib.js" ></script>
<script type= "Text/javascript" src= "Jquery.js" ></script>

<script type= "Text/javascript" >
$.noconflict ();
Code that uses the $ of another library

Can be used in conjunction with the. Ready () method and does not require an alias for the JQuery object, a technique that works well:

<script type= "Text/javascript" src= "Other_lib.js" ></script>
<script type= "Text/javascript" src= "Jquery.js" ></script>

<script type= "Text/javascript" >
$.noconflict ();
JQuery (document). Ready (function ($) {
Code that uses JQuery $
Code that uses $ from another library

In addition, by passing the argument true to the method, we can return the control of $ and jQuery back to the original library. Before use, please think clearly!

This is a more extreme version of the simple Noconflict method, because it will completely redefine jQuery. This is often used in extreme situations, such as you want to embed jQuery in a highly conflicting environment. Note: After calling this method, it is highly likely that the plug-in will fail.

Map the object referenced by $ back to the original object:

Jquery.noconflict ();

JQuery ("div p"). Hide (); Using JQuery

$ ("content"). Style.display = "None"; Use a different library's $ ()

Revert to use alias $, and then create and execute a function that still uses $ as the alias for JQuery in the scope of this function. In this function, the original $ object is not valid. This function is useful for most plug-ins that do not depend on other libraries:

Jquery.noconflict ();

(function ($) {
$ (function () {
Use $ as a jQuery alias code
}) (JQuery);

...//other libraries with $ alias as the code

You can combine jquery.noconflict () with shorthand ready to make your code more compact:

Jquery.noconflict () (function () {
Code that uses JQuery

...//Other libraries use $ to alias code

Create a new alias to use the JQuery object in the next library:

var j = jquery.noconflict ();

J ("Div p"). Hide (); JQuery-based Code

$ ("content"). Style.display = "None"; $ () code based on other libraries

Move JQuery completely to a new namespace:

var dom = {};
Dom.query = Jquery.noconflict (true);


Dom.query ("div p"). Hide (); Code for new JQuery

$ ("content"). Style.display = "None"; Code for another library $ ()

JQuery ("div > P"). Hide (); Another version of JQuery's code

Below begins to analyze Jquey source code:

Map over jQuery into case of overwrite
_jquery = Window.jquery,

Map over the $ in case of overwrite
_$ = window.$,

This paragraph is written in the jquery constructor, the main purpose of which is to save the possible jquery and $ variables, and it is very likely that other libraries will avoid conflicts

Noconflict:function (deep) {
if (window.$ = = jQuery) {
window.$ = _$;

if (deep && window.jquery = = jQuery) {
Window.jquery = _jquery;

return jQuery;

The deep parameter is a Boolean value if true to free jquery for undefined in the previous example has shown

window.$ = = JQuery

This condition is to ensure that only when jquery also has the control of $ to release, there is no release and meaningless, the _$ again into a global variable, and this $ may be other libraries so that the process of release

Deep && Window.jquery = = JQuery

Deep is true and jquery variables are also jquery, and, like $, if freed, there is no need to release

return jQuery;

The result of the execution is jquery, so that jquery can be used as a

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.