问题
The DOM NodeList (as returned e.g. by element.getElementsByTagName) is an interesting object, in that it is not a snapshot, but reflects changes to the document made after you have created the NodeList.
I was wondering how one would implement such a collection: Completely lazy evaluation must be horribly slow, but keeping a cached version consistent requires a lot of book-keeping internally.
I tried to google for blog articles on the subject, and also tried to find the relevant source code files for Mozilla, but could not find anything immediately (and when I cannot find something immediately, I come here...).
So how do Firefox, Safari, Internet Explorer (and other non-browser DOM implementations) handle NodeLists?
回答1:
For .NET's XML library, there are 3 internal subclasses of XmlNodeList with different strategies. The XmlChildNodes collection, for the XmlNode.ChildNodes property, uses simple lazy evaluation based on a reference to its containing element. The XmlElementList uses event listeners for when the DOM changes. The third, XPathNodelList, is for XPath queries (e.g., XmlNode.SelectNodes()) and evaluates the XPath each time its index is accessed, its Count property is read, or it is iterated.
来源:https://stackoverflow.com/questions/300794/how-is-the-nodelist-implemented