示例: 函数作为参数
// program to pass a function as a parameter function greet() { return 'Hello'; } // passing function greet() as a parameter function name(user, func) { // accessing passed function const message = func(); console.log(`${message} ${user}`); } name('John', greet); name('Jack', greet); name('Sara', greet);
输出
Hello John Hello Jack Hello Sara
在上面的程序中,有两个函数:
name()
和
greet()
。
name()
函数接受两个参数。
greet()
函数作为参数传递给 name()
函数。