地理定位函数参数行为

Geolocation function parameters behavior

我正在使用 google 映射 api,我注意到在 JavaScript:

中我不熟悉的编程行为
function success(pos) {
  // ...do something with pos.
}

navigator.geolocation.getCurrentPosition(success);

在上面的示例中,成功函数似乎是凭空传递了一个 'pos' 参数,并且没有通过括号在 getCurrentPosition 参数内部调用成功函数。我希望看到这样的东西:

function success(pos) {
  //...do something with pos.
}

var pos = //...something;
navigator.geolocation.getCurrentPosition(success(pos));

我只是不明白这是怎么回事。参数从何而来,为什么函数甚至不带括号调用?

这是您将在 Javascript 中经常看到的功能。它通常被称为回调。缺少括号是因为 Javascript 允许您将函数视为变量,通常称为 'first-class functions'。您正在将 success 函数传递给 getCurrentPosition 方法,您实际上并没有调用 success 方法。

当您调用 navigator.geolocation.getCurrentPosition(success); 时,您是在告诉 getCurrentPosition 函数,当它找到位置时,您希望它调用您提供的函数并将位置传递给它得到了。

getCurrentPosition 方法将执行如下操作:

function getCurrentPosition(successCallback) {
    var position = loadFromSomewhereThatMayTakeAWhile();
    successCallback(position);
}

getCurrentPosition 可能需要很多秒甚至几分钟才能获取当前位置。您不希望浏览器在发生这种情况时停止响应。回调允许你说 "when this operation has finished, call this other method to do something with the result"。然后浏览器可以继续处理其他事情,并且仅在操作完成时执行您的回调。

jQuery ajax函数使用了这种回调方式。

var whenSuccessful = function(data, status, xhr){
    console.log('The data was loaded successfully.')
};

var whenFailed = function(xhr, status, error){
    console.log('The request failed!')
};

$.ajax({
  url: "http://myserver.com/some_data.json",
  error: whenFailed, // do this if the request fails for any reason
  success: whenSuccessful // do this if the data was loaded successfully
})