views:

335

answers:

2

jQuery objects act like arrays without polluting native prototypes. How is this achieved?

I know it's not just objects with numeric keys - so perhaps it's just a matter of providing the respective methods (something like jQuery.prototype.indexOf = Array.prototype.indexOf).

I've googled and looked at the source, but couldn't find a definitive answer.

+2  A: 

Look in jquery code (development), line 139:

// Force the current matched set of elements to become
// the specified array of elements (destroying the stack in the process)
// You should use pushStack() in order to do this, but maintain the stack
setArray: function( elems ) {
    // Resetting the length to 0, then using the native Array push
    // is a super-fast way to populate an object with array-like properties
    this.length = 0;
    Array.prototype.push.apply( this, elems );
        return this;
},

This is because any result of jquery queries is array.

Anatoliy
Thanks. I'd seen this as well, but it doesn't seem to suffice:var MyObj = function(args) { this.length = 0; Array.prototype.push.apply(this, arguments); return this;};var obj = new MyObj("hello", "world");
AnC
Don't return `this` from a constructor! Also, `var` sets a variable, but it does not return a value; if you are executing that snippet in a Firebug-like tool: `var MyObj = function(args) { this.length = 0; Array.prototype.push.apply(this, arguments); }; obj = new MyObj("hello", "world");`
Alex Barrett
I'm confused: If it's not a constructor, "this" won't be the object (just window) though!? Can you provide a working sample?
AnC
`MyObj` _is_ a constructor, that's the point! And that is a working sample :)
Alex Barrett
Sorry, I misread your earlier statement.However, your code there doesn't seem to work for me: obj.indexOf is undefined - also, obj is not being displayed as an array in Firebug. Am I missing something?
AnC
I will post an answer explaining Firebug's behaviour, give me a few minutes.
Alex Barrett
+10  A: 

Although jQuery objects act like arrays, they are actually only array-like objects. An array-like object is an object using numeric keys and having a length property - that is the minimum needed for compatibility with the native Array methods.

Because jQuery objects are only array-like and not actual Array objects, native Array operations - like indexOf or reverse - cannot be called directly. You can circumvent this by using the Array prototype, or by extending jQuery's functionality.

$('div').reverse(); // TypeError: $("div").reverse is not a function

// we can use Array.prototype though
Array.prototype.reverse.apply($('div'));

// or we can extend jQuery very easily
$.fn.reverse = Array.prototype.reverse;
$('div').reverse(); // now it works!

You are correct in your assumption that Firebug does not include any special-casing for formatting jQuery objects. A quick search reveals a relevant post on the Firebug mailing list. Assuming the information is still correct (the post is from January) Firebug will format an object as an array if it has a finite length and a splice method.

JQuery fulfils both of these criteria, but their implementation of splice is nothing more than a direct copy of the native Array method. It is undocumented, which means it's either only for internal use, or perhaps added solely for the purpose of tricking Firebug into formatting jQuery objects nicely.

Alex Barrett
This is excellent - thanks!I'd hesitate to add a splice method just to make it look pretty in Firebug, but that's just a minor detail. (PS: There's a typo in your post; you mention "slice" instead of "splice".)
AnC
Thank you - corrected. I only suggest that the `splice` method was added to jQuery specifically for Firebug because jQuery's 1.2 branch does _not_ expose such a method. Indeed, I do remember a short period of time in which my jQuery objects were not being formatted as `Arrays` in Firebug. Of course, the method's introduction in 1.3 may have just coincidence.
Alex Barrett