-1

In Firebug 2.0.9:

> $('div')
Object[div.constrain, div#container, div#logo-events.constrain.clearfix, ...]

But:

> function MyObject() {}
undefined
> new MyObject()
MyObject {}

Notice - curly braces instead of square. Why? Seems like jQuery object is "subclassed" from JavaScript Array. But how it is done?

UPDATE #0

I can achieve square brackets like that:

> MyObject.prototype = Array.prototype
[]
> new MyObject()
Object[]

Can somebody explain the meaning of this?

Gill Bates
  • 14,330
  • 23
  • 70
  • 138
  • Jquery applies a wrapper around the normal dom elements. It may display with square brackets. You can break out of the wrapper with $('div')[0] – Taplar May 20 '15 at 13:07
  • Or it may just be a firebug display thing. I just did it in my firefox console (not firebug) and a jquery selector returned Object{ ... } – Taplar May 20 '15 at 13:12

1 Answers1

0

In firebug, when you see "Object[]", it's because it's an "array-like object".

"Array-like objects are objects that can be interated (sic), i.e. have indexes (e.g. NodeList, DOMTokenList, jQuery node lists returned by $(...), etc.). The type of the object is shown in case it can be determined, otherwise 'Object'," - https://getfirebug.com/wiki/index.php/Display_of_JavaScript_values_and_DOM_items

Here I simulate this jQuery "array-like object" : Object[li, li, li] , by adding the splice and length properties of the Array.prototype.

//array of three "li" items : 
var items = document.getElementsByClassName("people")[0].childNodes;

var a = {splice:function(){}}; //  Object { splice=function()}
var j = 0;
for (var i = 0; i < items.length; i++) {
    if (items[i].nodeType == 3) { // type 3 = textnodes
        continue;
    }
    a[j] = items[i];  // "a" is "Object {...}"
    j++;
}
a.length = j;   // now "a" is "Object[li, li, li]"
trogne
  • 3,402
  • 3
  • 33
  • 50