作为参数传递的函数是否总是回调?的JavaScript [英] Are functions passed as parameters always callbacks? JavaScript

查看:137
本文介绍了作为参数传递的函数是否总是回调?的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有下面的代码,我在其中将两个函数作为参数传递给函数sayHi,请问这是回调的示例吗?

If I have the code below, where I pass two functions as a parameters into the function sayHi, is this an example of a callback?

我注意到有两种方法可以运行这些参数函数":如下所示,我们在定义它们的函数中调用它们(作为参数),或者在sayHi函数中调用参数.这是回调和匿名函数之间的区别吗?

I notice there are two ways of running these 'parameter functions': either as below, we I call the functions where they are defined (as arguments), or alternatively where I call the parameter in the sayHi function. Would this be the difference between a callback and an anonymous function?

function sayHi(name, testForTrue) {
    if (testForTrue == true) {
        console.log(name);
    }
}

sayHi(function() {
    return 'Zach'
}(), function() {
    return true;
}());

我可以得到相同结果的另一种方法如下.在这种情况下,我要在其他时间评估功能?两者之间有什么实际区别吗?

Another way I could get the same result, is as below. In this case I am evaluating the functions at a different time? Is there any practical difference between the two?

function sayHi(name, testForTrue) {
    if (testForTrue() == true) {
        console.log(name());
    }
}

sayHi(function() {
    return 'Zach'
}, function() {
    return true;
});

推荐答案

是的,以参数形式传递的函数始终是回调,即使其目的是同步调用 (cf Array.prototype.map ),而不是异步(参见window.setTimeout).

Yes, functions passed as parameters are always callbacks, even if the intention is that the function is called synchronously (c.f. Array.prototype.map) rather than asynchronously (c.f. window.setTimeout).

在您的第一个代码块中,您实际上实际上并不是在传递函数.您有两个立即调用的函数表达式,其中此上下文中的关键部分是立即调用.函数表达式在代码中出现的那一刻被调用,只有这些表达式的 results 传递给sayHi.

In your first code block you aren't of course actually passing functions. You have two immediately invoked function expressions, where the key part in this context is immediately invoked. The function expressions are called at the point they appear in the code and only the results of those expressions are passed to sayHi.

这篇关于作为参数传递的函数是否总是回调?的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆