问题
Why doesn't htmlCollection inherit from array? I understand that htmlCollection is a live collection, as opposed to an array which is a snapshot, but can't it still inherit from array?
There's the obvious way of converting an htmlCollection to an array, but that's converting it. It's not like that by default.
Update
This is regarding the comment below:
Possible duplicate of Is HTMLCollection An Array? – @winhowes
As explained in the comments, these two questions widely differ. The other question explains the difference between the two, which I also wrote in my question above. My question is, why doesn't JavaScript's default htmlCollection inherit from array.
The difference between the two questions is, the other question is 'what's the diff', my question is 'why is there a diff'.
回答1:
Q: "Why doesn't htmlCollection inherit from array?"
A: That's because htmlCollection is completely unrelated to JavaScript Arrays. The first is a DOM object created by DOM the later is created by JS Array constructor. Being unrelated to JS Array constructor, DOM htmlCollection will naturally not inherit anything from array.
htmlCollection length property is the only common property between them, however, contrary to Aray length, the DOM htmlCollection property is read only.
The part that most probably interests you the most, is the fact that htmlCollection can make use of most methods exposed by JS arrays. And can be directly assigned to HTMLCollection prototype, whose constructor, as you may see for yourself: points to JS Object constructor.
p.s.: The htmlCollection object is by far more similar to arguments object than anything else as they are both invoked by Object constructor, not the Array.
来源:https://stackoverflow.com/questions/37176343/why-doesnt-htmlcollection-inherit-from-array