I got another question regarding jQuery’s architecture. $('div') constructs a new jQuery object:
$('div') instanceof jQuery; // true
I’d like to know why it is possible to query it like an array, allthough it isn’t an array?
$('div')[0]; // returns the first div in the document as a DOM node.
$.isArray($('div')); // false
I just love this syntax, it looks so clean! I also noticed this returns the DOM nodes as an array:
console.log($('div'));
Can somebody explain me how to implement this behaviour to my own objects?
My own approach was to make an array with some methods like this:
var a = ['a', 'b', 'c'];
a.method = function(){ return 'test'; };
a; // ['a', 'b', 'c']
a[0]; // 'a'
a.method(); // 'test'
However this doesn’t seem to be the way jQuery does it as this is actually an array:
$.isArray(a); // true
I’d like to know how jQuery does this to learn and to see if it’s a better solution than mine.
A jQuery object is what we call a
Array-like object. That means, it indeed is a “true” object (infact, all “arrays” are objects in ECMAscript), but it owns certain properties which make it look like a “true” array. Those properties are.lengthproperty.splice()methodthose two facts are enough that most
js enginesconsoles will interpretate that object as array.Example:
If we now log our object
we get the typical jQuery’ish result
See that in action
but we are still able to call our method
.aNiceFunction()on that object. By pushing new elements with theArray.prototype.push()method onto our object, ECMAscript will automatically index those elements for us. That was short description what happens under the jQuery hood.One more word about “Arrays” in ECMAscript. There are no real arrays in this language (if we forget about typed arrays for a second). There is only
Object. If we have an object that inherits fromArray.prototypewe would almost call it an array. Everything we would have left to do is, set the.lengthproperty to0.