How can jQuery return an array and still have it be a jQuery object?

前端 未结 1 1214
粉色の甜心
粉色の甜心 2021-02-14 20:22

I am attempting to reproduce jQuery\'s (1.7.1) object structure, to better understand how it it works. I have the following code:

(function (window, undefined) {         


        
相关标签:
1条回答
  • 2021-02-14 21:00

    jQuery objects are array-like, so look and behave a lot like arrays, but are in fact just custom objects made to roughly equate to a collection of DOM nodes (except with added functionality). All the array-like functionality - length, slice() etc.. - is in fact added manually to the jQuery prototype (for which jQuery.fn is an alias), sometimes by calling an array function with the jQuery object as context

      slice = Array.prototype.slice,
      ...
      slice: function() {
        return this.pushStack( slice.apply( this, arguments ),
          "slice", slice.call(arguments).join(",") );
      },
    

    and sometimes by writing it from scratch. Look at the annotated code (probably a very useful resource for you - it covers v1.6.2 but I don't think anything too drastic has changed since then, except maybe the addition of $.callbacks) to see that this.length is set manually e.g.

    if ( selector === "body" && !context && document.body ) {
      this.context = document;
      this[0] = document.body;
      this.selector = selector;
      this.length = 1;
      return this;
    }
    

    the jQuery.buildFragment() method is also fundamental to how jQuery objects containing larger collections of DOM nodes are constructed.

    So to sum up, jQuery doesn't use arrays, it just looks like it does because much native array functionality has been replicated as properties of the jQuery prototype.

    0 讨论(0)
提交回复
热议问题