meo
meo

Reputation: 31249

Why does the push method work on a jQuery object?

var test = $();
test.push( $('div')[0] );

This works. Any idea why? Since push is a array method, I don't understand why this works in this case, any idea?

Is there a practical use for it since you can use .add() ?

Upvotes: 4

Views: 928

Answers (2)

user113716
user113716

Reputation: 322502

They borrow .push() from Array.prototype.

https://github.com/jquery/jquery/blob/1.6.2/src/core.js#L70

and

https://github.com/jquery/jquery/blob/1.6.2/src/core.js#L296

Example: http://jsfiddle.net/HgS2R/1/

var MyObj = function(){};
MyObj.prototype.push = Array.prototype.push;

var inst = new MyObj;

inst.push( "test" );

document.write( inst[ 0 ] + '<br>' + inst.length );  // test, 1

Just be aware that instances of your custom constructor won't behave identically to an actual Array.


EDIT:

With respect to the edit in your question, .push() is not identical to .add().

The .push() method is for adding a DOM element to an existing jQuery object.

The .add() method can accept a DOM element, or another jQuery object with 1 or more DOM elements, and it returns a new jQuery object with the new elements added.

It's more like a .concat().

Upvotes: 3

BoltClock
BoltClock

Reputation: 723729

I checked the source and found these chunks of code (with comments). Not sure if they answer your question:

// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice

Upvotes: 1

Related Questions