JavaScript 中的高阶函数
higher order function in javascript
我正在阅读《雄辩》一书来学习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()
功能吗?
then
和body
是参数。它们的值取决于传递给 unless
和 repeat
的值。因此,为了确定值是什么(即它们是否是函数(,您需要查看调用unless
和repeat
的位置以及传递给它们的值。
请记住,通常可以多次调用repeat
和unless
。对于每个函数调用,then
和 body
的值可以不同,但它们必须是函数期望的类型(数字、字符串、函数等(,否则它将无法正常工作。
它们在哪里定义?
在您的示例中,此处调用了repeat
和unless
:
repeat(3, function (n) {
unless(n % 2, function () {
document.write(n + " is even<br>");
});
});
您可以看到传递给 repeat
和 unless
的第二个参数确实是函数。
n
的价值是什么?
让我们看看调用函数的位置。该函数作为第二个参数传递给repeat
。 repeat
使用body
来引用第二个参数,稍后将其称为循环中的body(i)
。 i
将具有0
的值times - 1
。 times
是传递给repeat
的第一个参数,在您的示例中3
。因此,该函数将被调用多次(三次(,接收值0
、1
和2
。
一点解释。
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)
// | | | |
// |-----|--------------- |
// ------------------------|
- JavaScript 中的高阶函数
- 避免在JS中重复使用高阶函数
- 回调和高阶函数Javascript
- 什么's将命名函数传递给Javascript的正确方法's的高阶函数
- Javascript如何使用高阶函数和Map/Reduce函数来汇总多个数组
- 使用JavaScript中的高阶函数概念,用Python编写纯函数代码
- 在高阶函数 JavaScript 中传递参数
- 如何在 Javascript 中使用高阶函数反转数组
- Eloquent JavaScript,第 2 版,第 5 章高阶函数
- JS中的高阶函数
- GHCJS:如何使用 FFI 导入高阶 JavaScript 函数
- 这个高阶函数有什么问题
- 如何在 Indesign 脚本中使用像 Array.reduce() 这样的高阶函数
- 此函数如何修改另一个函数?(高阶函数)
- 在es6类中从高阶函数中定义一个方法
- 将其绑定到高阶函数中的原始对象
- 高阶函数中的Javascript对象克隆
- 通过更改起始索引并使用Javascript中的高阶函数递增2来操作2D数组
- 将函数传递给另一个函数时的高阶函数说明
- 了解Javascript中的高阶函数