JQuery source parses the conversion between jQuery objects and DOM objects

Keywords: Javascript JQuery Attribute

The jQuery object is a class array object that holds a reference to the corresponding DOM. We can either get the DOM node in an index directly with [], get the DOM node in an index with get method, or convert the jQuery object into an array at once with toArray(), for example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <script>
        var jObject = $('p');
        console.log(jObject[0].innerHTML)            //output:1
        console.log(jObject[1].innerHTML)            //output:2
        console.log(jObject.get(2).innerHTML)        //output:3
        console.log(jObject.toArray())               //output:Array(3) [ p, p, p ]     ;Each element is a DOM Node, equal to corresponding p element
    </script>
</body>
</html>

Converting a DOM object to a jQuery object is more convenient and can be done directly within the jQuery constructor as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <script>
        var p         =     document.getElementsByTagName('p'),        
            result    =    [];                                        
        for(let i = 0;i<p.length;i++)        result.push(i)        //getElementsByTagName Get is HTMLCollection An object is also an array of classes, and we convert it into an array format

        console.log( $(p) instanceof $ )                        //output true        ;Express $(p)Is a jQuery object
        console.log( $(p).size() )                              //output:3            ;because p There are 3 inside DOM element

        console.log( $(p[0]) instanceof $ )                     //output true        ;Express $(p)Is a jQuery object
        console.log( $(p[0]).size() )                           //output:1            ;Because we only passed in one p[0],Only one? DOM node
    </script>
</body>
</html>

The output is as follows:

The reason is detailed in the code, well, that's it

 

Source Code Analysis

writer by:Desert QQ:22969969

The conversion of DOM to jQuery objects is accomplished within the init() function inside jQuery as follows:

init: function( selector, context, rootjQuery ) {
  /*slightly*/
  // Handle $(DOMElement)
  if ( selector.nodeType ) {                  //selector Has Attributes nodeType,Then think selector yes DOM element,for example:$(document.getELementById('d'))
    this.context = this[0] = selector;            //Save the DOM Reference to node
    this.length = 1;                              //Set up length Attribute 1
    return this;                                  //Return this,Support chain operation
  }

  /*slightly*/

  return jQuery.makeArray( selector, this );  //This is the last logic, if selector Is an array or pseudo-array
},

makeArray is a function inside jQuery that converts an array of classes into real data as follows:

  makeArray: function( array, results ) {     //Convert a class array object to a real array
    var ret = results || [];                    //If results If not present, correct to empty array, initialize jQuery Executing here result Be equal to jQuery Object, that is, the one passed in above this

    if ( array != null ) {                      //Filter parameters array yes null,undefined Situation.
      // The window, strings (and functions) also have 'length'
      // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
      var type = jQuery.type( array );

      if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {    //If array No Properties length Or parameters array Is a string, or a function, or a regular, or Window object
        push.call( ret, array );                                                                                                        //Consider parameters array Not an array, not a class array object, calling array methods push()Insert this parameter into the return value ret End of.
      } else {
        jQuery.merge( ret, array );           //Otherwise, consider the parameter array Is an array or class array object, calling a method jQuery.merge()Merge this parameter into the return value ret in
      }
    }

    return ret;
  },

Finally, we return the array, because we passed this in the second argument, so makeArray returns this last

For conversion of jQuery object to DOM object, since jQuery itself is a class array object, we can get the index directly with []. For get and toArray methods, these operations are defined on the prototype of jQuery, that is, jQuery.fn, as follows:

jQuery.fn = jQuery.prototype = {  //Rewrite jQueyr.fn
  /*slightly*/
  toArray: function() {               //Will be current jQuery Objects are converted to real arrays, which contain all elements.
    return slice.call( this, 0 );
  },
  get: function( num ) {              //Return to the current jQuery An element at a specified position in an object or an array containing all elements,
    return num == null ?

      // Return a 'clean' array
      this.toArray() :

      // Return just the object
      ( num < 0 ? this[ this.length + num ] : this[ num ] );      //Return directly this[num],That is to use with us[]Same, just encapsulated
  },
  /*slightly*/
}

We can see that for get, it's taken directly from this [], and toArray calls the slice method of the array of classes to convert it to a real array

Posted by aditya2071990 on Sun, 01 Sep 2019 17:47:02 -0700