我试图了解回调函数的概念。
请说明两个代码段之间的区别
//callback function
function greeting(name) {
console.log('Hello ' + name);
}
function processUserInput(callback) {
var name = "Johny1";
callback(name);
}
processUserInput(greeting);
和第二个
function greeting(name) {
console.log('Hello ' + name);
}
function processUserInput() {
var name = "Johny2";
greeting(name);
}
processUserInput();
为什么通过简单功能可以实现相同功能的情况下,有人使用回调函数?
答案 0 :(得分:1)
在第一个示例中,您并未对函数进行硬编码。因此,将来processUserInput
可以接受其他功能,它将按预期工作。
//callback function
function greeting(name) {
console.log('Hello ' + name);
}
function goodbye(name) {
console.log('Bye ' + name);
}
function processUserInput(callback) {
var name = "Johny1";
callback(name);
}
processUserInput(greeting); // will output Hello Johny1
processUserInput(goodbye); // will output Bye Johny1
但是在第二种情况下,greeting
函数是硬编码的
因此,如果不更改greeting
函数的定义,就无法将greeting
更改为任何内容。
答案 1 :(得分:0)
如果简单功能是同步的,则回调是为异步代码设计的。这意味着不必在此简单函数上使用回调。