想象一下这样的代码:
function foo(data) {
// ... do something with data
}
function do(userInput, callback) {
callback(userInput);
}
function doWithReturn(userInput, callback) {
return callback(userInput);
}
// ...
do('Hello, World', foo);
doWithReturn('Hello, World', foo);
使用普通的 do() 而不是 doWithReturn() 有什么好处吗?
我问是因为,假设我们不知道 foo() 在内部做了什么(即它可能有一个 return 语句,也许它只是触发了一个哑巴alert(data)
),使用 doWithReturn 调用 foo() 总是看起来“更安全”,因为如果foo() 恰好返回一个值,不使用 doWithReturn 显然是错误的。