HealthLinks is your destination for reliable, understandable, and credible health information and expert advice that always keeps why you came to us in mind.

JavaScript By Example

106 40
It isn't only when you rewrite a function from within the function that you can then call the rewritten function from within the original function. Any function can call itself. The only thing that you need to concern yourself with if your function does call itself is that something changes in between the original call and when it calls itself. In the rewrite example the something that changed was the content of the function itself but you can call exactly the same function from within itself provided that the parameters you pass into the function are different in some way from those of the original call and there is some mechanism within the function for it to eventually stop calling itself.


If you don't do this then the function will keep calling itself forever and will eventually crash and none of the code after the function will ever run.

In this example we have a function that will add the content of each text node that it finds to an array and which will call itself whenever it finds an element node that has any content so that it can extract any text nodes contained within that element. As elements can be nested we have the function call itself to handle when it finds elements within elements. We know that the function will eventually stop calling itself because it only calls itself when it finds nested elements and the elements in any web page are not infinitely nested (as that would require an infinite number of tags).

var node, txtnodes; nodewalk = function(node, str) { if (typeof str != 'array') str = []; for (var i = 0; i < node.length; i++) { if (node[i].hasChildNodes() && 'SCRIPT' !== node[i].nodeName) str = nodewalk(node[i].childNodes,str); if (3 === node[i].nodeType) str.push(node[i]); return str; } txtnodes = nodewalk(document.getElementsByTagName('body')[0]);

Source...

Leave A Reply

Your email address will not be published.