JQuery Source code Analysis and use experience-core.js

Source: Internet
Author: User

Core is the central content of jquery, including the most basic methods, such as our common $ (selector, context), for traversal operations of each, map, EQ, first recognition variable type IsArray, IsNumeric, type, etc. . These methods provide the most basic support for jquery follow-up operations.

Constructor JQuery (selector, context)

When it comes to jquery, what you probably know best is $ (selector, context), and I think that's a big part of how jquery is popular, because it's very powerful.

    // Define A local copy of JQuery    function (Selector, context) {        // The JQuery object is actually just the Init constructor ' enhanced '         //  need init if jQuery is called (just allow error to being thrown if not included)        re Turnnew  jQuery.fn.init (selector, context);    },

Here we obviously see a keyword is new, which means that every call to $ () will be new to a jquery object, some people may not notice this will write the following code, or will appear $ ("#id") = = = $ ("#id") This judgment, This kind of writing is not advisable, we should try to save the number of jquery, and re-use jquery object.

if ($ (". Class"). Hasclass ()) {    $ (". Class"). Removeclass ();}
Static Properties and Prototype properties

Two types of attributes can be seen from Core.js (Q: Functions are also properties Oh!), a class of static properties defined with Jquery.extend ({}), a class of prototype properties defined by Jquery.fn = Jquery.prototype = {}. A static property is a property of the jquery function, called by a call, such as $.each. Static properties are typically tool methods that are not related to page elements. The prototype attribute is a function of extending the jquery object, which holds the jquery object itself (this), as var $a = $ ("a") for processing its own object; $a. each (). (Q: There are two each in jquery, to distinguish)

Concrete implementation methods are relatively simple, it is no longer one by one narrative. Jquery.extend is a very common method that combines several objects into one object and supports both deep and shallow copies in two ways that are often used when doing some default configuration and implementation.

jquery Object creation

By looking at the jquery (selector, context) function, we know that jquery has called New JQuery.fn.init (selector, context).  In this sentence there is a comment: Need init if jQuery is called. We found init.js under the/src/core/directory. The content is roughly as follows

init = JQuery.fn.init =function(Selector, context) {//  ...    //  ...    return  This; // ...Retrun This. Constructor (context). Find (selector); // ...    return(Context | |rootjquery). Find (selector); // ...    return typeofRootjquery.ready!== "undefined"?Rootjquery.ready (selector)://Execute immediately if ready are not presentselector (jQuery); // ...    returnJquery.makearray (Selector, This ); }//Give the init function The JQuery prototype for later instantiationInit.prototype = Jquery.fn;

There are many kinds of returns in this method.

The first of this, which returns the object of Init;

The second type of jquery object. Find (); /src/traversing/findfilter.js:find, return This.pushstack, return Jquery.merge (This.constructor (), ele MS); jquery Object

The third type of selector (jQuery); does not necessarily return jquery objects

Fourth species of Rootjquery.ready (selector); /src/core/ready.js:ready, return this (Rootjquery), jquery object

Fifth type Jquery.makearray (selector, this); var ret = results; return ret; jquery Object

From the above observation, it is found that there is only one case where the jquery method returns not a jquery object: the passed-in selector parameter is an object, and the/src/core/ready.js module is not loaded. The following code will also demonstrate this (the code will be in the attachment, please update it in time).

<!DOCTYPE HTML><HTML>    <Head>        <MetaCharSet= "Utf-8">        <title>Core</title>    </Head>    <Body>        <Scriptsrc= "Require.js"Data-main= "Main"type= "Text/javascript"CharSet= "Utf-8"></Script>        <Scripttype= "Text/javascript"CharSet= "Utf-8">require (['.. /src/core/init'], function(init) {varret= NewInit (function() {                    return{name:"Not jquery"                    };                });            Console.log (ret); })        </Script>    </Body></HTML>

In the first case, return this returns the Init object, not the JQuery object, but we see below init.prototype = Jquery.fn; So the object created by Init is the jquery object.

jquery implements a pseudo-array

We use jquery as an array in many cases. But from the creation process above, jquery seems to have nothing to do with arrays. So let's analyze his prototype and see why jquery can be used like an array.

Before I introduce "duck type (Duck typing)" (Q-June: Duck?), what is duck type? "When you see a bird walking like a duck, swimming like a duck and barking like a duck, the bird can be called a duck." "This is a very appropriate description, in a dynamic language we do not need to tube an object exactly what type, as long as he can execute a method, then I can think that he is a type of object."

JavaScript is one such language. To implement an array, you do not have to inherit or use an array object. As long as you implement the method inside the array object, you can think of it as an array. Here I also found a very interesting thing. When debugging with chrome, we output a different format when we use Console.log to output ordinary objects and arrays. The output object is similar to "F {length:0}" and the output array is similar to "[1]". Let's experiment with the following lines of code.

 var  f = function  () {this . length = 1; this    [0] = "a" }console.log ( new  f ()); //  f {0: "a", length:1}  var  f = function  () {this . length = 1; this . Splice = function  () {};this  [0] = "a" }console.log ( new  F   ()); //  [" a "]  

Ha, how magical! Chrome thinks of him as an array! If the length in an object is a number and splice is the method, the object will be considered an array by chrome. If you are interested, try the other browsers.

Well, we look back at the prototype of jquery, the prototype of jquery contains the usual length attributes in the array, push, sort, splice, slice, and so on.

All jquery is used just like an array.

Usage recommendations

1. Minimize the reuse of the $ () method to get the same object

2. $ () Most will return jquery objects, but do not rule out in extreme cases

3. jquery can be used as an array, but not exactly an array, pop, shift, etc. methods are not applicable to jquery objects.

Attachment

Http://yunpan.cn/Q7nKEsZ9cqFby Extract Code 3A4A

JQuery Source code Analysis and use experience-core.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.