$

Is the main function of jQ, the property methods are all based on the main function of jQ, the property methods are all based on mount. After the introduction of jQuery, when using jQuery, it usually adopts the normal function execution method of $([selector]), but returns an instance object. Generally, the constructor of new execution returns an instance object. Here, the encapsulation of jQuery() function adopts factory mode to make objects

(function(){
    "use strict";
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = some methods, shortcut name = = = = = = = = = = = = = = = = = = = = = = = = = = =
    var arr = [];
    var slice = arr.slice;
    var push = arr.push;
    var indexOf = arr.indexOf;
/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = jQ constructor declaration, and deal with its prototype object = = = = = = = = = = = = = = = = = = = = = = = = = = =
    var 
         version = "3.5.1 track of",
         jQuery = function( selector, context ) {
           /** * selector is a CSS selector, context is limited to which DOM container to find (not required) * $(xx) returns an instance created by the new execution of the init constructor on the prototype */
           return new jQuery.fn.init( selector, context );
         };
        // take an alias, fn is an alias for prototype, and redirect the prototypejQuery.fn = jQuery.prototype = {... }/ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = init constructor = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
     var
         // root The default value is rootjQuery
          rootjQuery,
          rquickExpr = / ^ (? :\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/./** * &&internal implementation of init function * 1. Init function mounted on jQuery prototype * 2. The instance object that returns init is also an instance object of JQ. Init prototype redirection guarantees $() after execution of jQ instance object * 3. User convenience $(...) /new $(...) New * 4. The jq instance object is an array of classes. The instance private attributes are index and Length. Jq [number] can get the native DOM object */
          init = jQuery.fn.init = function( selector, context, root ) {
            root = root || rootjQuery;
            // Do not pass selector, return empty JQ instance object
            if ( !selector ) {
              return this;
            }
            / / * * * * * * * * * according to the different types of return jq, supports three types of the selector, small parser * * * * * * * * *
            
            
            
            var match,elm;
            // Selector is a string
            if ( typeof selector === "string" ) {
              / / $(" < XXX >... 
      ") HTML character template
              if ( selector[ 0= = ="<" &&
                selector[ selector.length - 1= = =">" &&
                selector.length >= 3 ) {
                  match = [ null, selector, null ];
              }
              // Fit normal selectors (eg: '. Box ', '#app'...)
              else {
                match = rquickExpr.exec( selector );
           
                // Parse the specific string
                // Match html or make sure no context is specified for #id
                if ( match && ( match[ 1) | |! context ) ) {// HANDLE: $(html) -> $(array)
                  if ( match[ 1 ] ) {
                    context = context instanceof jQuery ? context[ 0 ] : context;
                    // Option to run scripts is true for back-compat
                    // Intentionally let the error be thrown if parseHTML is not present
                    jQuery.merge( this, jQuery.parseHTML(
                        match[ 1 ],
                        context && context.nodeType ? 
                        context.ownerDocument || context : document.true));// HANDLE: $(html, props)
                    if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
                      for ( match in context ) {
                        // Properties of context are called as methods if possible
                        if ( isFunction( this[ match ] ) ) {
                          this[ match ]( context[ match ] );
                        } 
                        / /... and otherwise set as attributes
                        else {
                          this.attr( match, context[ match ] ); }}}return this;
                  } 
                  // HANDLE: $(#id)
                  else {
                    elem = document.getElementById( match[ 2
                    if ( ele
                      // Inject the element directly into the jQuery object
                      this[ 0 ] = elem;
                      this.length = 1;
                    }
                    return this; }}// HANDLE: $(expr, $(...) )
                else if ( !context || context.jquery ) {
                  return ( context || root ).find( selector );
                }
                // HANDLE: $(expr, context)
                // (which is just equivalent to: $(context).find(expr) 
                else {
                  return this.constructor( context ).find( selector ); }}// Selector is a DOM object type that returns an array of objects
            else if(selector.nodeType) {
              // Add this native DOM as an attribute of the returned JQ object {0: selector}
              this[ 0 ] = selector;
              Don't forget to add the length attribute
              this.length = 1;
              // Returns the jq object (new explicitly returns the object, which is an array of classes).
              // The native DOM can be found on the returned JQ object so that the JQ prototype method can be used
              return this;
            }
            
            
            
            
            // Selector is a function type that returns the result of the ready execution
            else if(isFunction(selector)) {
              // Ready listens for the DOMContentLoaded event, and then executes the selector after the DOM is loaded
              // Execute the callback fn or direct selector passed to ready(fn)
              / / $(function () {}) - equivalent to -- > $(document). Ready (function () {})
              returnroot.ready ! = =undefined ?
              root.ready( selector ) : selector( jQuery );
            }
            
            
            
            
            // Selector does none of the above, creates an array of jQ classes and returns it. Eg: nodeList set --> Jq set
            return jQuery.makeArray(selector, this)}// Redirect the prototype of the init function to the jQuery prototype so that instances of new init can use the properties method on the jQuery prototype
          init.prototype = jQuery.fn;
          rootjQuery = jQuery( document); ./ / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = mount = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
        window.jQuery = window.$ = jQuery; }) ()Copy the code

Instance methods

Use with $(‘ XXX ‘).xxx (example)

jQuery.fn = jQuery.prototype = {
   jquery: version,
   // Redirect constructor
   constructor : jQuery,
   length: 0
   // Append some array methods to the prototype, jQ instances can use (instances that want to borrow methods from other classes can append their methods to the prototype object)
   push: push,
   sort: arr.sort,
   splice: arr.splice,
   
   // jq.get(pass number) gets the native DOM object of the specified index
   get: function( num ) {
     if ( num == null ) {
        // Returns an array of all DOM collections on the jq array without specifying an index
        return slice.call( this );
     }
     // Support positive and negative indexes
     return num < 0 ? this[ num + this.length ] : this[ num ];
   },
   
   // jq.eq(passing numbers) looks for a particular item in a JQ object and returns a new JQ object.
   eq: function( i ) {
     var len = this.length,
     // Negative index is supported
     j = +i + ( i < 0 ? len : 0 );
     return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
   },
   
   pushStack: function( elems ) {
     // this.constructor() returns an empty JQ object. Merge appends all items in elems to the empty JQ
     var ret = jQuery.merge( this.constructor(), elems );
     // prevObject records the original operation. The chain call returns a new pointer that can be used to return to the original JQ object
     ret.prevObject = this;
     // return the merged Jq
     return ret;  
   },
   
   // Append the second array to first and return first
   merge: function( first, second ) {
    var len = +second.length,
        j = 0,
        i = first.length;
    for(; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i;return first;
  },
  
  / / ready
  jQuery.fn.ready = function( fn ) {
    // The readyList mechanism is similar to promise. Listen on DOMCOntentLoaded, wait for the DOM structure to load, and then execute fn
    readyList
      .then( fn )
      .catch( function( error ) {
        jQuery.readyException( error );
      });
    / / return the $(document)
    return this;
};
}
Copy the code

Function object methods

Use (example) with $.xxx()

/** * &extend jQuery methods * When you need to customize some custom methods, or develop jQuery plug-ins to complete the JQ library, you need to use $.extend() method to do so. * This method can be called either on a jQuery function object or on a jQuery instance

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

	//$.extend({... }) : pass only one object, target = this object, deep = false
	// $.extend([boolean], {... }) : pass the first item as Boolean, the second item as object, same as above, but deep = true
	if (typeof target === "boolean") {
		deep = target;
		target = arguments[i] || {};
		i++;
	}

	// Make sure target is an object
	if (typeoftarget ! = ="object" && !isFunction(target)) {
		target = {};
	}

	// Target is transferred to the extend caller, $or $.fn, regardless of how many arguments are passed
	if (i === length) {
		target = this;
		i--;
	}

	// Only loop once
	for (; i < length; i++) {
		// Get the object passed in as the parameter
		if ((options = arguments[i]) ! =null) {
			for (name in options) {
				// clone each key-value pair: {name: copy}
				copy = options[name];
				// Cloning prevents infinite recursion
				if (name === "__proto__" || target === copy) {
					continue;
				}
				// deep is true, (copy exists and is an ordinary object) or (copy is an array)
				if (deep && copy && (jQuery.isPlainObject(copy) ||
					(copyIsArray = Array.isArray(copy)))) {
					// Get the attribute value corresponding to the original name on the jQ function /jQ prototype
					src = target[name];
					// Copy is an array, but the original name is not an array
					if (copyIsArray && !Array.isArray(src)) {
						clone = [];
					}
					// If the copy passed is not an array, the value of the original name attribute is not an object
					else if(! copyIsArray && ! jQuery.isPlainObject(src)) { clone = {}; }else {
						clone = src;
					}
					copyIsArray = false;
					// clone each item
					target[name] = jQuery.extend(deep, clone, copy);
				}
				// deep is not true, extend the key-value pair for jQ function /jQ prototype, if the same name is also replaced directly
				else if(copy ! = =undefined) { target[name] = copy; }}}}// Return the processed jQ function /jQ prototype
	return target;
};




/** * & traversal method: similar to forEach in arrays, used to traverse ordinary objects, class arrays, and arrays * Extend the traversal method to jQ function objects using the extend method above */
jQuery.fn = jQuery.prototype = {
  ...
  // $([selector]).each(()=>{}) instance call
  each: function( callback ) {
    return jQuery.each( this, callback );
  }
}

jQuery.extend({
  ...
  / / $. Each ($(/ selector), function (key/index, value) {}) static call
  each: function (obj, callback) {
    var length, i = 0;
    typeof callback === 'function' ? callback = Funtion.prototype : null;
    // obj is a class array/array
    if ( isArrayLike( obj ) ) {
	length = obj.length;
	for(; i < length; i++ ) {// Each time the item is iterated, the callback executes, and this refers to the current array/class item
            // I -> index, value -> value
            // Support callback function return value, once return false, terminate traversal
            if ( callback.call( obj[ i ],  obj[ i ], i ) === false ) {
                    break; }}}// obj is an ordinary object, as above
    else {
      // for ( i in obj ) {
      // The extended property methods that might be traversed here in the owning class will be traversed
      // if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
      // break;
      / /}
      // } 
      // Get only private attributes
      var keys = [
        ...Object.getOwnPropertyNames(obj), 
        ...Object.getOwnPropertySymbols(obj)
      ]
      for(; i <= keys.length-1; i++) {
        var key = keys[i],
            value = obj[key];
        if(callback.call( value, key, value ) === false) {
          break; }}}returnobj; }})Copy the code