Skip to content Skip to sidebar Skip to footer

How Does Jquery Invoke Methods Of Objects When An Array Of Jquery Objects Is Returned?

After passing a string 'selector' into the jQuery function: $('#onenode') An array of jQuery object's is returned. One of the methods of these object's is 'html', which is why: $(

Solution 1:

jQuery is basically a big prototype with a bunch of methods that return this, where this is the instance of jQuery you're working with.

I am attempting to create my own small library that uses "selectors"

Here's a very reduced example of a jQuery-like pattern that works in modern browsers:

(function(win, doc) {

  var __slice = [].slice;

  functionjQuery(selector) {
    this.el = this._init(selector);
    this.length = this.el.length;
  }

  function$(selector) {
    returnnewjQuery(selector);
  }

  jQuery.prototype = {

    _init: function(selector) {
      return __slice.call(doc.querySelectorAll(selector));
    },

    each: function(fn) {
      returnthis.el.some(fn), this;
    },

    map: function(fn) {
      returnthis.el.map(fn), this;
    }

  };

  win.$ = $;

}(window, document));

You can use that to build your jQuery like library. It works exactly like jQuery:

$('p').each(function() {
  console.log(this);
});

A currying function, each and map is all you need to get started. Those are the methods the jQuery uses pretty much everywhere to manipulate DOM elements. this.el is the array of elements while this is the jQuery instance. Just don't forget that you need to return this in every method that will be chained.

Solution 2:

$('.somenodes') does not return an array, its a jquery object only, which have some functions of native array..

I also had similar doubt some time back, check this answer on my question..https://stackoverflow.com/a/11158649/1114536

jQuery objects currently support 3 array methods:

var methods = 'pop push reverse shift sort splice unshift concat join slice toString indexOf lastIndexOf filter forEach every map some reduce reduceRight'.split(' ')
var implemented = $.grep(methods, function(m) {
    return $.prototype[m] == Array.prototype[m];
});
console.log(implemented); // => ["push", "sort", "splice"]

They also have slice, but it's not the same slice as arrays have:

$.prototype.slice === Array.prototype.slice// => false

Post a Comment for "How Does Jquery Invoke Methods Of Objects When An Array Of Jquery Objects Is Returned?"