[英]what's the difference between calling a function and passing a function?
This conversation came up at work today and I wasn't completely able to grasp the difference, and my google search so far has been fruitless. 这次对话今天开始进行,我还不能完全理解其中的区别,到目前为止,我的Google搜索一直没有结果。
The example that was used at work was the difference between 在工作中使用的示例是
DoSomethingFunction().then(function(){ DoSomethingElse(); });
and 和
DoSomethingFunction().then(DoSomethingElse());
To me, I look at the first, and it's an anonymous function, so that would just get called and inside it, is the function we want to call, but that's why I used the second version, which just calls the function without wrapping it in a separate function. 对我来说,我看第一个,它是一个匿名函数,因此将被调用并在其中,这是我们要调用的函数,但这就是我使用第二个版本的原因,第二个版本只调用该函数而不包装它在一个单独的功能。
Can somebody explain the difference to me? 有人可以向我解释差异吗?
Functions in JavaScript are objects, and can be passed around just like any other object. JavaScript中的函数是对象,并且可以像其他任何对象一样传递。
DoSomethingElse
is a function object that can be executed with DoSomethingElse()
. DoSomethingElse
是可以通过DoSomethingElse()
执行的功能对象。
.then
expects a function object, so the following just executes the function and returns its value or undefined
if it returns nothing: .then
需要一个函数对象,因此以下代码仅执行该函数并返回其值;如果不返回任何值,则undefined
:
// this is wrong, unless `DoSomethingElse` returns a function
DoSomethingFunction().then(DoSomethingElse());
The following passes an anonymous function (this is what .then
expects, a function), then executes DoSomethingElse
inside. 下面的代码传递一个匿名函数(这是
.then
期望的函数),然后在内部执行DoSomethingElse
。
DoSomethingFunction().then(function(){
DoSomethingElse();
});
The following passes the function object to then
, and does the same as the above: 以下将函数对象传递给
then
,并执行与上面相同的操作:
DoSomethingFunction().then(DoSomethingElse);
Passing a function means, that a function is passed as an argument, and it can be called in the called function. 传递函数意味着将函数作为参数传递,并且可以在被调用函数中调用它。 Calling a function means that the function body is executed, and it returns a value.
调用函数意味着函数主体已执行,并返回一个值。 In your example
在你的例子中
DoSomethingFunction().then(DoSomethingElse());
you pass the result of a function call, so the result of calling DoSomethingElse
(the return value). 您传递了函数调用的结果,因此传递了
DoSomethingElse
(返回值)的结果。 In case of 的情况下
DoSomethingFunction().then(DoSomethingElse);
you pass a function, which then needs to be executed in the then
function to get it's result. 您传递了一个函数,然后需要在
then
函数中执行该函数才能获取结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.