Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an empty jQuery object: $({}) or $()

I have seen the following two variable initializations to create an empty jQuery object. Is there a major difference or advantage to use one over the other?

var a = $({});
var b = $();
like image 279
John Haldson Avatar asked Oct 31 '12 01:10

John Haldson


2 Answers

If you meant $([]), that's something from the old days where calling $() was actually equivalent to $(document) (which was an undocumented feature). So to get an empty set, you'd have to call $([]). This was changed in jQuery 1.4; the documented functionality of $() is now to return an empty set.

Passing objects to the jQuery constructor is an entirely different beast. $({}) doesn't create an empty jQuery object. It creates a jQuery object with a length of 1; the selected item is the object itself.

Passing JS objects to the jQuery constructor lets you take advantage of a more esoteric feature of jQuery: binding and triggering events on (non-DOM) objects.

For example:

var obj = { some: 'stuff' };

$(obj).on('someevent', function() { ... });

$(obj).trigger('someevent');

Either way, if your goal is to instantiate a new, empty jQuery object, use $().

like image 194
josh3736 Avatar answered Sep 28 '22 21:09

josh3736


I think you mean:

var a = $([]); //<- array not object
var b = $();

No advantage that I know of, the first one is the old version, since 1.4 you can use the later.

like image 21
elclanrs Avatar answered Sep 28 '22 21:09

elclanrs