1

Given that you can access a jQuery object's members using array-like bracket syntax: $myjQueryObject[0], it seems like jQuery extends the built-in Array object. However, I can't seem to find where they do this, in the jquery.js file.

I've successfully accomplished something similar by extending the Array 'class', just curious how jQuery does it!

Michael Lewis
  • 4,252
  • 6
  • 28
  • 39
  • 1
    [You can't really subclass Array.](http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/) JQuery doesn't do it either - it just fakes the "length" property. – Pointy Nov 03 '13 at 18:42
  • possible dupe: http://stackoverflow.com/questions/15457928/how-does-jquery-invoke-methods-of-objects-when-an-array-of-jquery-objects-is-ret?rq=1 lemme read this before anyone answers – Michael Lewis Nov 03 '13 at 18:43
  • What about the bracket syntax? Does it just create numeric indexes? – Michael Lewis Nov 03 '13 at 18:43
  • 1
    The bracket syntax is just part of the language, and yes it uses numeric property names. (All property names, even in arrays, are technically strings anyway.) – Pointy Nov 03 '13 at 18:44
  • I made an object with the `Array` as a prototype that seemed to work, but I didn't thoroughly test it. I'm curious to read that link and see what's up, thanks! – Michael Lewis Nov 03 '13 at 18:48
  • There'll be quirks. It can be faked with using property getters and setters, but should be fully supported in ECMAScript 6. – Blue Skies Nov 03 '13 at 18:50
  • Here's another dupe that's only now showing up in related questions: http://stackoverflow.com/questions/1483445/how-do-jquery-objects-imitate-arrays?rq=1 – Michael Lewis Nov 03 '13 at 18:51
  • 1
    @MikeLewis the main things that's hard is keeping the "length" property correctly set to match the numeric property names. – Pointy Nov 03 '13 at 18:57

1 Answers1

2

Any object can access its properties via [] notation.

var obj = {};

obj["foo"] = "bar";
obj[1]=  "baz";

In JavaScript, an Array is just a specialized object, so its [] syntax is the same as any other object.

In addition, the Array.prototype methods are generic by specification. They can be applied to any "array-like" object, meaning any object that has a numeric .length and numeric indices.

var obj = {"1": "bar", "0": "foo", "2": "baz"};

var arr = Array.prototype.slice.call(obj, 1);

console.log(arr); // ["bar", "baz"]
Blue Skies
  • 2,935
  • 16
  • 19