Javascript理解回调函数和执行

时间:2016-07-10 03:08:55

标签: javascript callback

我有script1script2。以下是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?为什么我不能只返回值?

2 个答案:

答案 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');
}