jquery Source code Analysis (a)

Source: Internet
Author: User

jquery makes it easier for users to work with DOM, events, animations, and to provide Ajax interactivity to websites.

2, jquery's module dependency network:

jquery is a total of 13 modules, modules are not single, such as jquery animation, will rely on the asynchronous queue, animation queue, callback queue and data cache module.

jquery pulls out all the reusable features, separating out a single module, and using a combination of methods, jquery is very clever in both design and implementation.

Five chunks: selectors, dom manipulation, events, Ajax and animations

So why are there 13 modules? Because one of the most favorite things to do in jquery design is to pull together a common feature to make it "modular",

And, of course, the "single Responsibility SRP", which is closer to the five principles of S.O.L.I.D, and the advantage of following a single duty is that we can easily maintain this object,

For example, when an object encapsulates a lot of responsibilities, once a function needs to be modified, it will inevitably affect the object's other responsibility code.

Decoupling allows each responsibility to change more flexibly.
Let's take a look at the jquery document provides a series of façade interfaces for the processing of the business layer's Ajax:

. Ajaxcomplete (). Ajaxerror (). Ajaxsend (). Ajaxstart (). Ajaxstop (). Ajaxsuccess ()

Bottom-Level interface:

Jquery.ajax () Jquery.ajaxsetup ()

Quick Method:

Jquery.get () Jquery.getjson () Jquery.getscript () Jquery.post ()

design principle of jquery interface

Business logic is complex, and jquery has a lot of high-level API, and is very meticulous, so that it can be more user friendly to facilitate the operation of the developer,

There is no need to overload too many actions on one interface. We're looking inside. The high-level approach to Ajax is actually a unified call to a static Jquery.ajax method,

The code is shown in the right-hand code editor (27-43 lines).
The internal implementation of Jquery.ajax is very complex, first of all, Ajax to consider the unity of asynchronous processing and callbacks,

So we introduce the asynchronous Queue module (Deferred) and the callback module (callbacks), so we need to encapsulate these module methods inside the Ajax method again,

Constructs a new JQXHR object, for the default processing of parameters, data transmission format and so on.

Second: Call the expression immediately

The first point of any library and frame design is to solve the problem of namespace and variable pollution.

jquery is the use of JavaScript function scope of the characteristics of the immediate invocation of an expression wrapped in its own way to solve the problem.

The immediate invocation function expression of jquery is written in three ways:

Notation 1:

(Function (window, factory) {    Factory (window)} (this, function () {    return function () {       //jquery call    }}) )

It can be seen that the above code is nested in 2 functions, and passing a function as a parameter to another function and execution, this method is a bit complicated, we simplify the wording:

Notation 2:

var factory = function () {    return function () {        ///Execute method    }}var jQuery = Factory ();

The code effect above is equivalent to Method 1, but this factory is a bit of a simple factory method pattern that needs to be called by itself, not like a single jquery class, so we need to change to "self-executing" instead of calling it separately.

Notation 3:

(Function (window, undefined) {    var jQuery = function () {}    //...    ) Window.jquery = window.$ = JQuery;}) (window);

As you can see from the code above, this function is initialized automatically, so that it is built only once. Give me a detailed look at the advantages of this notation:

1,window and undefined are to reduce the scope scope of variable lookup. When the window is passed to the inside of the closure,

When you use it inside a closure, you can think of it as a local variable, which is obviously faster than if you were looking under window scope.
2,undefined is the same truth, in fact, this undefined is not a JavaScript data type undefined, but an ordinary variable name.

Just because the value is not passed to it, its value is that undefined,undefined is not a reserved word for JavaScript.

Why pass undefined?

Undefined in Javascript is not a keyword, so you can allow users to assign a value to it.

var undefined = ' Service ';(function (window) {alert (undefined);//ie8 ' Service '}) (window)

IE8 There is this problem, of course, most browsers are not modifiable

If the function call is not passed, the parameter defaults to undefined

;(function (window,undefined) {    //undefined}) (window)

Why does jquery create such an outer package, and how does it work?

Here to distinguish 2 concepts one is an anonymous function, and the other is self-executing. As the name implies, an anonymous function is a function without a function name, that is, there is no external reference. But is it implemented as follows:

function () {//code logic}

The above is wrong, declares it but does not give the name and no use, so syntactically wrong, then how to execute an anonymous function?
To invoke a function, we must have a way to locate it and reference it. So, we're going to take a name:

var jQuery = function () {//code logic}

jquery uses () to enclose the anonymous function, followed by a pair of parentheses (including the argument list), then the parentheses can combine our expressions into chunks,

And each piece (that is, each pair of parentheses) has a return value. This return value is actually the return value of the expression in parentheses.

So, when we enclose the anonymous function with a pair of parentheses, the actual parentheses return is the function object of the anonymous functions.

Therefore, the parenthesis pair plus the anonymous function is like the name of the function that we get its reference position.

So if you add a parameter list after the reference variable, the invocation form of the normal function is implemented.

Finally, we go back to writing 1 to see how jquery uses notation 3, and then pass the entire function as a parameter to another function.

The main purpose is to judge the load logic of jquery under different platforms, and mainstream libraries generally have support codes for AMD and CommonJS, and look at the code for jquery:

if (typeof module = = = "Object" && typeof module.exports = = = "Object") {    module.exports = global.document? 
   
    factory (Global, true):        function (w) {            if (!w.document) {                throw new Error ("jQuery requires a window with a doc Ument ");            }            Return Factory (w);    };} else {    factory (global);}
   

Summary: The global variable is the Devil, anonymous function can effectively guarantee to write JavaScript on the page, without causing the pollution of global variables,

By enclosing the parentheses, it is initialized immediately when it is loaded, thus creating a singleton pattern effect that will only be executed once.

jquery Source code Analysis (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.