潘俊杰 潘俊杰 - 4 months ago 7
jQuery Question

Why can I access HTMLElement from jQuery Object with array index operator?

As I've tested,

$('foo')
is an instance of
jQuery
, and not an instance of
Array
. And AFAIK, javascript doesn't have operator overloading.

So how can
$('foo')[0]
return the corresponding
HTMLElement
if
$('foo')
is not an instance of
Array
?

I tried to look at jQuery's source code but it's a bit too much for me right now.

Thanks for any insight.

Answer

Because you can use brackets notation with any object in JavaScript, not just arrays. In fact, normal arrays aren't really arrays at all in JavaScript, they're just objects with a specific prototype and special treatment of a class of property names ("array indexes") and a special length property.

Brackets notation can be used to access any object property1 via its string name (and believe it or not, [0] is converted to ["0"] when accessing arrays, in theory).

Example:

var obj = {foo: "bar", 0: "zero"};
console.log(obj[0]);     // zero
console.log(obj["0"]);   // zero
console.log(obj.foo);    // bar
console.log(obj["foo"]); // bar
var f = "f" + "o" + "o";
console.log(obj[f]);     // bar

The object above has two properties of its own. Their names are "0" and "foo"; both names are strings (even though I wrote 0 as a numeric literal in the initializer; it gets coerced to string).

jQuery maintains its "array entry" properties to ensure that you can use brackets notation to access them. It also maintains a length property.

If jQuery were being written from scratch today, it probably would extend Array. But when jQuery was written, you couldn't extend Array. (It only became possible as of ES2015's ("ES6's") class feature.)


1 Except properties that don't have a string name; ES2015 introduced the concept of properties with names that are Symbols rather than strings. Prior to that, all object property names were strings (even array indexes).

Comments