Home  >  Article  >  Web Front-end  >  In-depth analysis of the core functions in jquery

In-depth analysis of the core functions in jquery

零下一度
零下一度Original
2017-06-17 17:49:091401browse

Core functions include:

How jquery is defined, how to call it, and how to extend it. Mastering how the core methods are implemented is the key to understanding the jQuery source code. Everything suddenly became clear here.

1, how to define, that is, the entrance

// Define a local copy of jQuery

var jQuery = function(selector, context) {

// The jQuery object is actually just the init constructor 'enhanced'

return new jQuery.fn.init( selector, context, rootjQuery ); // The jQuery object is actually just the constructor FunctionjQuery.prototype.init enhanced version

}

2, jQuery prototype, and its relationship with jQuery.fn.init

//Define object method, that is, it can only be called through $("xx").

jQuery.fn = jQuery.prototype = {

init:function( selector, context, rootjQuery ) {

return jQuery.makeArray( selector, this );

}

There are many other properties and methods,

Properties include: jquery, constructor, selector, length

Methods include: toArray,get, pushStack,each, ready,slice, first,last,eq, map,end, push, sort, splice

}

//put jQuery.prototype is assigned to jQuery.prototype.init.prototype for later instantiation

// Give the init function the jQuery prototype for later instantiation

jQuery.fn.init.prototype = jQuery.fn;

That is, $("xx") has an instance method and can be called. (Call the method defined under jQuery.prototype)

Why does jQuery return the jQuery.fn.init object?

jQuery = function( selector, context ) {

// The jQuery object is actually just the init constructor 'enhanced'

return new jQuery.fn.init( selector, context, rootjQuery );

}

jQuery.fn = jQuery.prototype = {

……

}

jQuery.fn.init.prototype = jQuery.fn;

Find similar questions on stackoverflow :

http://stackoverflow.com/questions/4754560/help-understanding-jquerys-jquery-fn-init-why-is-init-in-fn

And this

http://stackoverflow.com/questions/1856890/why-does-jquery-use-new-jquery-fn-init-for-creating-jquery-object-but-i-can/1858537#1858537

I believe the code is written in this fashion so that the new keyword is not required each time you instantiate a new jQuery object and also to delegate the logic behind the object construction to the prototype. The former I believe is to make the library cleaner to use and the latter to keep the initialisation logic cleanly in one place and allow init to be recursively called to construct and return an object that correctly matches the passed arguments.

3, extend extended object method and static method principle

jQuery.extend = jQuery.fn.extend = function() {

var target = arguments[0] || {};

Return target;

}

It is convenient to use extend, which is nothing more than $.extend({}); and $.fn.extend({}); If you It would be great if you could understand and think of jQuery.prototype when you see fn.

Let’s look at this scope again:

$.extend ->this is $-> this.aa()

$.fn.extend-> ;this is $.fn-> this.aa()

Attached extend implementation details:

Usage scenarios:

1, extend some functions

Only one parameter. For example: $.extend({f1:function(){},f2:function(){},f3:function(){}})

2, merge multiple objects into the first object

(1) Shallow copy, the first parameter is the target object. For example

var a = {name:”hello”}

var b = {age:30}

$.extend(a,b);//a= {name:”hello”,age:30}

(2) Deep copy, the first parameter is TRUE, and the second parameter is the target object. For example

var a = {name:{job:”it”}};

var b = {name:{age: 30 }};

//$ .extend(a,b);

$.extend(true,a,b);

console.log(a);

jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

    // 是不是深复制  Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[1] || {};
        // skip the boolean and the target
        i = 2;
    }

    // 不是对象类型  Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
        target = {};
    }

    // 扩展插件的情况  extend jQuery itself if only one argument is passed
    if ( length === i ) {//$.extend({f1:function(){},f2:function(){},f3:function(){}})
        target = this;//this是$,或是$.fn
        --i;
    }

    for ( ; i < length; i++ ) {//可能有多个对象扩展到第一个对象上
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {//options是一个对象
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];  //src是target里已经存在的value(也可能不存在)
                copy = options[ name ];//copy是待合入的一个value

                // 防止循环引用  Prevent never-ending loop
                if ( target === copy ) {//例如:var a={};$.extend(a,{name:a});//可能导致循环引用
                    continue;
                }

                // if是深复制else是浅复制  Recurse if we're merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray(src) ? src : [];

                    } else {
                        clone = src && jQuery.isPlainObject(src) ? src : {};
                    }

                    // 亮了,直至剥离至最深一层非对象类型,而且是逐个。Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );

                // Don't bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;//target[ name ] = options[ name ];
                }
            }
        }
    }

    // Return the modified object
    return target;
};

jQuery. extend({...}) analysis

Look at how it is written

jQuery.extend({

prop:””

method:function( ){}

});

It can be seen that these methods are static properties and methods of jQuery (that is, tool methods). In the future, they can be provided directly to users or For internal use.

The specific implemented tool properties and methods are (also marked which ones are used internally)

jQuery.extend({

expando : Generate unique JQ string(internal)

noConflict() : Prevent conflicts

isReady : Whether the DOM has been loaded (internal)

readyWait : Counter of how many files to wait for (internal)

holdReady() : Delay DOM trigger

ready() : Prepare for DOM trigger

isFunction() : Whether it is a function

isArray() : Whether it is an array

isWindow() : Whether it is a window

isNumeric() : Whether it is an array Number

type() : Determine the data type

isPlainObject() : Whether it is an object argument

isEmptyObject() : Whether it is an empty object

error() : Throw an exception

parseHTML() : Parse node

parseJSON() : Parse JSON

parseXML () : Parse XML

noop() : Empty function

globalEval() : Global parsing JS

camelCase() : Convert camel case

nodeName( ) : Whether it is the specified node name (internal)

each() : Traverse the collection

trim() : Remove leading and trailing spaces

makeArray() : Convert a class array to a true array

inArray() : Array version indexOf

merge() : Merge arrays

grep() : Filter new array

map() : Map new Array

guid : unique identifier (internal)

proxy() : change this to point to

access() : multi-function value operation (internal)

now() : Current time

swap() : CSS swap (internal)

});

jQuery.ready.promise = function(){}; Monitoring Asynchronous operation of DOM (internal)

function isArraylike(){} Array-like judgment (internal)

The above is the detailed content of In-depth analysis of the core functions in jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn