我对下面的以下代码有些困惑。我不了解的部分是result参数如何等于的结果callback(x+y)
。有人可以解释一下,也可以解释一下执行的步骤顺序吗?
function add(x,y, callback){
callback(x+y)
}
add(3,4, function(result){
console.log(result) //logs out 7
})
我知道3 + 4是7,但我不特别了解result参数如何获得此7值。
很好的问题,一旦您理解了这一点,它将为Javascript打开许多大门。
让我们看看没有回调的情况:
function add(x, y) {
return x + y;
}
add(1, 2) // returns 3
当您使用时return x + y
,这就是您从函数中获得的回报。
现在让我们介绍一个新函数,但不作为回调。
function add(x, y) {
return x + y;
}
function logResult(result) {
console.log(result)
}
var result = add(1, 2) // 3
logResult(result) // outputs "3"
如您所见,我们调用add
,获取结果,然后将其传递到中logResult
,然后将其输出到控制台。
如果我们logResult
在的第三个参数中作为函数传递add
,然后在内add
将result
其调用,则实际上是同一件事!
function add(x, y, callback) {
var result = x + y;
// we're calling the function that gets passed in
// which is `logResult`
callback(result)
}
function logResult(result) {
console.log(result)
}
add(x, y, logResult) // outputs "3"
现在我们回到您的示例,该示例将所有内容减少到所需的最少代码:
function add(x, y, cb) {
cb(x + y);
}
add(1, 2, function (result) {
console.log(result)
}); // outputs "3"
在JS中,您可以将函数传递给其他函数。接收另一个函数作为参数的函数可以调用它。那就是你在这里。您还可以进一步减少:
function add(x, y, cb) {
cb(x + y)
}
add(1, 2, console.log) // outputs "3"
add(1, 2, console.error) // outputs "3" in error format
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句