Skip to main content

Bug Tracker

Side navigation

#320 closed feature (wontfix)

Opened October 28, 2006 01:05PM UTC

Closed November 10, 2006 04:18PM UTC

Why not make jQuery objects inherit directly from Array?

Reported by: henra..h+jquery@gmai Owned by:
Priority: minor Milestone: 1.0
Component: core Version: 1.0
Keywords: Array inheritance Cc:
Blocked by: Blocking:
Description

Since jQuery objects now store their current element-list on numeric indices, it seems logical to make the jQuery 'class' inherit directly from Array. This way, we get all the array methods for free (push, pop, shift, unshift etc) for use in internal logic.

We get a clean, fast way to clone/convert to a plain array (the slice method with no arguments), instead of using jQuery.merge(jqObj, []).

And we get this interesting result:

($('body>div') instanceof Array) === true

... which means that existing functions which perform type-checking will see a jQuery object as a legitimate Array instance, because essentially it ''is'' one.


None of this would really matter, of course, if the inheritance wasn't so ''super'' easy to implement:

1. define jQuery.extend before jQuery.prototype instead of afterwards, like so:

jQuery.extend = function(obj,prop) {
	if ( !prop ) { prop = obj; obj = this; }
	for ( var i in prop ) obj[i] = prop[i];
	return obj;
};

2. Then, when defining the prototype (and making sure it still gets jQuery.fn.extend as a method like it normally would), wrap the properties onto a fresh, blank array, instead of just an object literal:

jQuery.fn = jQuery.prototype = jQuery.extend([], {
	jquery: "1.0.2",
	extend: jQuery.extend,

		... other functions ...
});

3. ...and that's it.

Good idea? Terrible idea? just plain pointless?

I know I like it.

Attachments (0)
Change History (5)

Changed October 28, 2006 01:16PM UTC by henra..h+jqu comment:1

Whoops -- I should have pointed out that this would also mean inheriting reverse and sort, corresponding to the request in ticket #255

Changed October 28, 2006 01:21PM UTC by anonymous comment:2

keywords: → Array inheritance
milestone: → 1.0
version: → 1.0

Changed October 30, 2006 02:36PM UTC by anonymous comment:3

A patch is now available here. Final filesize difference: 28 bytes.

Changed October 30, 2006 10:11PM UTC by dave.methvin comment:4

Did you try this on IE6?

Changed November 10, 2006 04:18PM UTC by henra..h+jqu comment:5

resolution: → wontfix
status: newclosed

Oh god, the magic length value. I thought there was some way around that but there isn't. Oh well.