A script was needed to quickly tell me how many html comments there are on the page and what their contents are. Using an anonymous function for recursive DOM traversal seemed appropriate:
var comments = []; //set up an array where comment contents will be copied to
(function(D) {
if (8===D.nodeType) comments.push(D.nodeValue); //check if node is a comment
D=D.firstChild;
while (D) {
arguments.callee(D); //recursively look for comments...
D=D.nextSibling; //...and remember to iterate over all children of any node
}
})(document);
console.log(comments.join("\r\n")); //list all comments
Fiddle works as expected, but I was curious if it was really the same function called over and over, or were there multiple references to the original function called, or were there multiple identical functions called... After all, there has been no named reference made, so how would it work as the traversal goes deeper? I thought I may be able to check that by adding the following code into while (D) {...}
//tmpCallee has been declared
if (tmpCallee) {
console.warn(arguments.callee === tmpCallee);//true
/*great, means these should be both pointing to the same function*/
console.log(arguments.callee === arguments.caller);//false
/*wait, what? didn't we just establish above that
all of our functions called recursively would be the same?*/
console.log(arguments.caller);//undefined... but it was called recursively!
console.log(arguments.callee);//prints our function code verbatim as it should
}
tmpCallee = arguments.callee;
I'm confused. 1) am I really calling the same function over and over or are there multiple identical functions called or is something else at play? 2) why does arguments.caller
not point at our function? it was clearly invoked by it - that's how recursion works, no?