高阶函数外一则
[html]
<head>
<script type='text/javascript'>
function temperature() {
return current
}
hot = function hot() {
alert('Hot.')
}
cold = function cold() {
alert('Cold.')
}
current = hot
function swap() {
if(current == hot) {
current = cold
} else {
current = hot
}
}
</script>
</head>
<body>
<button onclick="funct = temperature()();">Temperature</button>
<button onclick="swap();">Swap</button>
</body>
[/html]
将函数用作函数的参数,或将函数作为值返回,这些概念属于高阶函数的领域。
这个例子解决了一个常见问题:如何将更改中的行为附加到用户接口事件?通过高阶函数,这很容易做到。temperature 高阶函数返回 current 的值,而 current 又可以有 hot 或 cold 函数。看一下这个有些陈旧的函数调用:temperature()()。第一组括号用于调用 temperature 函数。第二组括号调用由 temperature 返回 的函数。