好吧,有时你不知道函数的调用者是谁,直到它被调用 - 这排除了传递预先计算的值。
浮现在脑海中的几个例子是:
(a) setTimeout 或 setInterval - 您想在指定时间段后调用特定函数,可以是一次性的,也可以是重复的。如果调用的函数返回一个依赖于时间的值,则在某些情况下您可能无法预先计算该值 - 它需要在预定时间完成。因此,我们告诉函数在指定时间调用我们自己的哪些函数。
(b) 在加载(或至少尝试)各种资源时。我们可以给元素一个函数,加载成功时执行,加载失败时执行另一个函数。在调用这两个(用户提供的)函数中的任何一个之前,您实际上并不知道加载资源的工作何时完成。在有许多资源的情况下,您可以在此处增加保持成功/失败加载尝试次数的计数器。
(c) 调用 getElementsByClass 或 getElementsByTagName 返回的 NodeList。它不是一个实际的(javascript 原生)Array 对象。因此,您不能像使用数组一样调用 forEach 方法。为了解决这个问题,我使用以下辅助函数:
// getElementsByTagName, getElementsByClass - both return a NodeList
// it is accessed in the same way as an array - with the [] operators, but it's
// not an array object - this is a function that allows us to still iterate through it
// in much the same way.
function forEachNode(nodeList, func)
{
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
func(nodeList[i], i, nodeList);
}
}
这允许我获取节点列表,然后在每个节点上调用一些用户定义的函数。在使用中,它看起来像这样:
var allAnchors = document.getElementsByTagName('a');
forEachNode(allAnchors, showNodeTextVal);
function showNodeTextVal(curElem, curIndex, origList)
{
alert(curElem.innerText);
}
或者更简单地说:
var allAnchors = document.getElementsByTagName('a');
forEachNode(allAnchors, function(curElem){alert(curElem.innerText);} );
与我们不使用这个辅助函数相比,这是一个更清晰、更不容易出错的情况。为了实现相同的功能,我们需要编写以下代码:
var nodeList = document.getElementsByTagName('a');
var i, n = nodeList.length;
for (i=0; i<n; i++)
{
alert(nodeList[i].innerText);
}