Bug Tracker

Opened 16 years ago

Closed 16 years ago

#320 closed feature (wontfix)

Why not make jQuery objects inherit directly from Array?

Reported by: [email protected] Owned by:
Priority: minor Milestone: 1.0
Component: core Version: 1.0
Keywords: Array inheritance Cc:
Blocked by: Blocking:


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.

Change History (5)

comment:1 Changed 16 years ago by henra..h+jqu

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

comment:2 Changed 16 years ago by anonymous

Keywords: Array inheritance added
Milestone: 1.0
Version: 1.0

comment:3 Changed 16 years ago by anonymous

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

comment:4 Changed 16 years ago by dave.methvin

Did you try this on IE6?

comment:5 Changed 16 years ago by henra..h+jqu

Resolution: wontfix
Status: newclosed

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

Note: See TracTickets for help on using tickets.