简体   繁体   English

返回值回调函数?

[英]Returning a value of callback function?

I'm having some trouble with function callbacks, specifically with the HTML5 geolocation API. 我在使用函数回调时遇到了一些麻烦,特别是HTML5地理定位API。 I'm a little new to Js as well. 我也是Js的新手。 The function: 功能:

function getInfo()
{
    navigator.geolocation.getCurrentPosition(getPos);
}

takes a callback parameter of a function that gets the position passed into it. 获取一个函数的回调参数,该函数获取传递给它的位置。

function getPos(position)
{
PositionObj.lat = position.coords.latitude;
PositionObj.lon = position.coords.longitude;
}

I created a "location" object to store the coordinates, and I'm having trouble returning them. 我创建了一个“位置”对象来存储坐标,我很难返回它们。

var PositionObj = 
{
lat:null,
lon:null,
returnLat: function()
             {
             return this.lat;
             },
returnLon: function()
             {
             return this.lon;
             }
};


function printStuff()
{
getInfo();
console.log(PositionObj.returnLat());
}

EDIT: Syntax mistakes fixed. 编辑:语法错误修复。 When I call printStuff(), I still get "null." 当我调用printStuff()时,我仍然得到“null”。

  • To pass the callback, use just getPos instead of calling the function right away. 要传递回调,请使用getPos而不是立即调用该函数。
  • Use proper syntax to declare properties in PositionObj . 使用适当的语法在PositionObj声明属性。

PositionObj = {
    lat: null,
    lon: null,
}

Your PositionObj literal is incorrect. 您的PositionObj文字不正确。 the initial properties should be set with colons: 初始属性应使用冒号设置:

{ lat: '', lon: '' }

The callback should tell you that the request to get position information is asynchronous. 回调应告诉您获取位置信息的请求是异步的。 This means that getInfo() does NOT set the values instantly, and therefore the following line cannot access the "new" values. 这意味着getInfo()不会立即设置值,因此以下行不能访问“新”值。

Anything that relies on the result of an asynchronous function MUST be within the callback itself. 任何依赖于异步函数结果的东西都必须在回调本身内。

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

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