简体   繁体   English

为什么在成功函数的末尾不需要'()'?

[英]Why is it not required to have '()' at the end of the success function?

I got the following code: 我得到以下代码:

navigator.geolocation.getCurrentPosition(
  successFunction
);

I was wondering why it is not required to use the '()' at the end of the succesFunction? 我想知道为什么在succesFunction的末尾不需要使用'()'? Isn't it required to call a function with the '()' --> somefunction() What's the logic behind it? 使用'()'-> somefunction()调用函数不是必需的吗?

因为您传递的是函数引用,而不是函数的返回值。

A function is a thing that can be invoked—where it runs code and returns a result. 函数是可以被调用的东西 ,它在其中运行代码并返回结果。 You invoke a function by using the parentheses. 您可以通过使用括号来调用函数。 But, if you want to talk about the thing, if you want to pass the function around so that someone else can invoke it, you leave off the parentheses. 但是,如果您要谈论事物,并且想要传递该函数以便其他人可以调用它,则可以省略括号。

In this case, the getCurrentPosition() function is asking you to give it a function so that it can call it later on. 在这种情况下, getCurrentPosition()函数要求您为其提供一个函数,以便以后可以调用它。 So instead of invoking successFunction, you pass along a reference to it. 因此,您传递的是引用而不是调用successFunction。

If you instead wrote: 如果您改为:

navigator.geolocation.getCurrentPosition(
  successFunction()
);

…then what would happen is successFunction() would be invoked—the code of the function would be run, and possibly return a value—and THEN you would invoke getCurrentPosition() , passing along as an argument whatever value successFunction returned. …然后将发生的情况是,将调用successFunction() —函数的代码将运行,并且可能返回一个值—然后,您将调用getCurrentPosition() ,并将successFunction返回的任何值作为参数传递。

In JavaScript you can pass functions as objects: 在JavaScript中,您可以将函数作为对象传递:

Try executing this example: 尝试执行以下示例:

function myFunction() {
    console.log('hello');
}

function anotherFunction(functionParameter) {
    console.log('executing function passed as argument:');
    functionParameter();
}

anotherFunction(myFunction);

This code will print: 此代码将打印:

"executing function passed as argument:"
"hello"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM