我有script1
和script2
。以下是script1
的一些代码:
var pos;
function foo(param){pos = param;}
bar(foo);
现在在script2
:
function bar(callback){
//prints 'function'
console.log(typeof callback);
navigator.geolocation.getCurrentPosition(
success,
fail
);
}
function success(position, callback){
//prints 'undefined'
console.log(typeof callback);
var pos= {
lat: position.coords.latitude,
long: position.coords.longitude
};
callback(pos);
}
如何正确地将foo
作为回调函数传递给bar
,并将其链接到navigator.geolocation.getCurrentPosition
?如何正确地将pos
恢复为script1
?为什么我不能只返回值?
答案 0 :(得分:3)
您需要将回调重新传递给成功函数
function bar(callback){
//prints 'function'
console.log(typeof callback);
navigator.geolocation.getCurrentPosition(
function(pos){
// repass callback to success method
success(pos, callback);
},
fail
);
}
答案 1 :(得分:0)
var pos;
function foo(param){pos=param; console.log(param);}
bar(foo);
function bar(callback){
//prints 'function'
//console.log(callback);
navigator.geolocation.getCurrentPosition(
success.bind(null, callback),
fail
);
}
function success(callback, position){
//prints 'function'
var pos= {
lat: position.coords.latitude,
long: position.coords.longitude
};
callback(pos);
}
function fail(){
console.log('failed');
}