Below is code from Douglas Crockford’s The Good Parts.
For most part the code makes sense. Except, I don’t understand this line here:
var walk_the_DOM = function walk(node, func) {
as it appears the function is given two names – walk_the_dom() and walk()
Further down you can see the code is actually called both ways so that indeed both of these names reference the function.
Why is this function given two names?
// Define a walk_the_DOM function that visits every
// node of the tree in HTML source order, starting
// from some given node. It invokes a function,
// passing it each node in turn. walk_the_DOM calls
// itself to process each of the child nodes.
var walk_the_DOM = function walk(node, func) {
func(node);
node = node.firstChild;
while (node) {
// walk() called here
walk(node, func);
node = node.nextSibling;
}
};
// Define a getElementsByAttribute function. It
// takes an attribute name string and an optional
// matching value. It calls walk_the_DOM, passing it a
// function that looks for an attribute name in the
// node. The matching nodes are accumulated in a
// results array.
var getElementsByAttribute = function (att, value) {
var results = [];
// walk_the_DOM() called here
walk_the_DOM(document.body, function (node) {
var actual = node.nodeType === 1 && node.getAttribute(att);
if (typeof actual === 'string' &&
(actual === value || typeof value !== 'string')) {
results.push(node);
}
});
return results;
};
This is in order for the recursion to work safely, I would imagine.
For example, if you wanted to only use the
walk_the_DOMname, the variable could be reassigned later on, or not accessible due to the scope, so it is not safe to use it inside of the function itself.UPDATE:
I’ve done some research, and here’s what I found. First of all, refer to ECMAScript 5 specification, section 13.
There are two ways to define a function: a) using FunctionDeclaration, and b) using FunctionExpression.
They look very similar, but are also somewhat different. The following is a FunctionDeclaration:
These two are both FunctionExpression:
The interesting part for us is about FunctionExpression. In case of
var y = function f() { }, the identifierfis only visible from inside the function body. In other words, anywhere outside of{ },typeof fwill returnundefined.Now it’s time for some practical examples. Let’s say we want to write a recursive function using FunctionDeclaration:
Now we want to “copy” the function to another variable and to set
f1to something else:But this doesn’t work as expected:
Now if you used the Douglas Crockford’s way of defining a recursive function:
This way you can reassign the function to any variable as many times you want. At the same time, we ensured that the function always calls itself, and not some function assigned to the variable
f1.So the answer to the initial question: you define recursive functions in this manner, because it is the most flexible and robust way.