陷入javascript变量闭包
Stuck in javascript variables closures
我只是想把position.coords.latitude和经度分配给lat和lon vars,但似乎我错过了一些东西,因为Console总是说lat-lon是未定义的。
function init()
{
var lat;
var lon;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
lon = position.coords.longitude;
});
}
console.log(lat);
console.log(lon);
}
问题是,当您像最初那样使用var
定义变量时,它们的值是未定义的。现在,当您调用getCurrentPosition
函数时,它可能是异步的,这意味着console.logs
在您实际分配任何值之前就被调用了。尝试以下更改
function init()
{
var lat;
var lon;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
lon = position.coords.longitude;
// Log them in the callback function
console.log(lat);
console.log(lon);
});
}
}
由于您希望在拥有coords之后执行实际的代码,以下是如何更改init函数以适应异步体系结构的方法。
// New function argument callbackFn - the function to call after
// coords are loaded
function init(callbackFn)
{
// Removed local variables, no need for them here
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// This will be logged after the async call completes, probably after
// the console.log call below
console.log("finished async call");
// Execute the callback with coords
callbackFn(lat, lon);
});
}
// This will be called as soon as JS steps over previous lines,
// but before the asynchronous request has completed
console.log("finished init");
}
让我们假设当您执行一个名为start with latitude和经度的函数时,您的实际程序就开始了。在这种情况下,您将使用以下程序启动您的程序:
function start(latitude, longitude) {
// ... SNIP ... DO SOMETHING COOL
}
init(start);
我想navigator.geolocation.getCurrentPosition()是异步的,所以在您尝试写入控制台时它不会执行。
尝试将控制台写入移动到回调函数中:
function init()
{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
});
}
}
相关文章:
- 子类访问父类's闭包变量
- 构造函数函数闭包变量
- 如何冻结函数's在闭包中的变量
- 使变量可用于不带闭包的异步调用
- 局部变量在闭包中丢失
- 其中是闭包中存储的变量-堆栈或堆
- javascript闭包:保护内部变量
- Javascript:附加字符串中的事件,闭包中的变量求值
- "可变变量可从闭包“”访问;在传递给Array.prototype.every的函数中
- JavaScript闭包和变量引用
- Javascript分析之谜 - 闭包变量
- 对闭包变量的更改是否在使用闭包的回调中可见
- 使用object.assign()添加到对象中的getter发现闭包变量的值错误
- Javascript:为什么对闭包变量的访问可能很慢
- 模块中未更新Nodejs闭包变量
- node.js捕获闭包变量
- Javascript中绑定闭包变量
- 函数外部的Javascript闭包变量访问
- 回调函数访问闭包变量
- 为什么我的闭包变量在使用$后被清除.每个都使用JSON数据