JavaScript 中的高阶函数

higher order function in javascript

本文关键字:函数 高阶 JavaScript      更新时间:2023-09-26

我正在阅读《雄辩》一书来学习javascript。我遇到了这个例子

function unless(test, then) {
    if (!test) then();
}
function repeat(times, body) {
    for (var i = 0; i < times ; i++) body(i);
}
repeat(3, function (n) {
    unless(n % 2, function () {
        console.log(n, " is even ");
    });
});
// → 0 is even
// → 2 is even

我知道函数可以作为参数传递,并且可以彼此内部。但是then()body()功能吗?它们在哪里定义?n的价值是什么?

但是then()body()功能吗?

thenbody是参数。它们的值取决于传递给 unlessrepeat 的值。因此,为了确定值是什么(即它们是否是函数(,您需要查看调用unlessrepeat的位置以及传递给它们的值。

请记住,通常可以多次调用repeatunless。对于每个函数调用,thenbody 的值可以不同,但它们必须是函数期望的类型(数字、字符串、函数等(,否则它将无法正常工作。

它们在哪里定义?

在您的示例中,此处调用了repeatunless

repeat(3, function (n) {
    unless(n % 2, function () {
        document.write(n + " is even<br>");
    });
});

您可以看到传递给 repeatunless 的第二个参数确实是函数。

n的价值是什么?

让我们看看调用函数的位置。该函数作为第二个参数传递给repeatrepeat使用body来引用第二个参数,稍后将其称为循环中的body(i)i将具有0的值times - 1times 是传递给repeat的第一个参数,在您的示例中3 。因此,该函数将被调用多次(三次(,接收值012

这里有

一点解释。

function unless ( test , then ) {
  if (! test ) then () ;
}
function repeat ( times , body ) {
  for ( var i = 0; i < times ; i ++) body ( i ) ;
}
// in here you also pass 2 params to repeat.
// 3 and an anonymous function, the function is the argument 'body' in repeat
repeat (3 , function ( n ) {
  // as you can see here - you pass 2 params to unless, 
  // 1 is the result of n %2, and an anonymous  function, the function is the argument
  // "then" in unless.
  unless ( n % 2 , function () {
    console . log (n , " is even ") ;
  }) ;
}) ;

n 的值从 0 变为 3 它,它将是 0,1,2

另外,由于您是初学者,我建议您使用 https://jsfiddle.net/来测试内容。

在这里的示例中,您有 unless 函数的签名:

function unless ( test , then ) {
// code here
}

测试然后都称为参数,并根据调用时传递的参数而变化unless

例如:

 function first(){}
 function second(){}
 unless(first,second)

表示除非是函数原因的测试内部test 替换为第一个函数,然后在调用 unless 时替换为第二个函数

// unless(test,then) => unless(first,second)
//         |     |              |        |
//         |-----|---------------        |     
//               ------------------------|