0

How jQuery('selector') returns an array but also supports chaining.

If jQuery returns array like object how does in its response it containts [element1, element2] instead of {0: element1, 1: element2} and how prototype is linked to [element1, element2]

Can someone provide a sample example creating custom object plugin which returns array and also have one childFunction method to support chaining.

Expected output:

var plugin = function(selector) { ///////Code comes here};

plugin('selector') // should return static array [1,2];
plugin('selector').childFunction('selector') // should return static array [1,2]
Pradeep Lakku
  • 241
  • 2
  • 7
  • 1
    *"How jQuery('selector') returns an array but also supports chaining"* - It doesn't return an array, it returns an array-like object with all of those other methods on its prototype, and all of the chainable methods also return objects of that same type. See the linked duplicate, or also [this question](https://stackoverflow.com/questions/25270851/how-does-jquery-chain-functions-while-still-returning-an-array?noredirect=1&lq=1) (amongst others). – nnnnnn Oct 18 '17 at 01:40
  • If Array like object means {0: element1, 1: element2} but in console its output is represented as [element1, element2] and we can't expand it to see if any prototype is attached to it – Pradeep Lakku Oct 18 '17 at 01:44
  • 1
    When I log a jQuery object to the console I *can* expand it to see its prototype. – nnnnnn Oct 18 '17 at 01:49
  • Thanks for your support but when I console jQuery('body').prototype, it's returning undefined. – Pradeep Lakku Oct 18 '17 at 02:12
  • Just log `jQuery('body')`, and then expand that and you should see it has a `__proto__` property that refers to its prototype. Or log `jQuery('body').__proto__`. A function's `.prototype` property defines the prototype that objects created by calling that function with `new` will be linked to, which is not what you are trying to check, you are trying to check the prototype of the object returned from the `jQuery()` function. `jQuery.prototype === jQuery('body').__proto__`. – nnnnnn Oct 18 '17 at 02:18
  • I am able to achieve the above requirement after adding a statement of Array method to the Constructor. I achieved the example working at http://plnkr.co/edit/tPQkA6N71CITNKXVLoqv?p=preview – Pradeep Lakku Oct 18 '17 at 09:57

0 Answers0