下面是来自 Douglas Crockford 的 The Good Parts 的代码。
在大多数情况下,代码是有意义的。除了,我在这里不明白这一行:
var walk_the_DOM = function walk(node, func) {
看起来这个函数有两个名字 -walk_the_dom()
和walk()
再往下,您可以看到代码实际上是双向调用的,因此这两个名称实际上都引用了该函数。
为什么这个函数有两个名字?
// 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;
};