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

查看:35
本文介绍了作为参数传递的函数总是回调吗?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) 而不是 异步 (cf 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).

在您的第一个代码块中,您当然实际上并没有传递函数.您有两个立即调用的函数表达式,其中该上下文中的关键部分是立即调用.函数表达式在它们出现在代码中的地方被调用,并且只有这些表达式的结果被传递给 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天全站免登陆