首页 > 请问javascript 中怎么给回调函数传值?

请问javascript 中怎么给回调函数传值?

例如我要使用geolocation的api,里面有getcurrentlocation方法,如何将外部定义的map传给successCallback内部?

var map = new googleMap
navigator.geolocation.watchPosition(successCallback,errorCallback,options);

function succesCallback(position){//这里position是默认的,我需要将外部定义的map引入,如果我加了新的传入参数会报错。
    map.latitude = position.coords.latitude
    map.longitude =  position.coords.longitude
}

期待解答


var map = new googleMap

map 是在全局作用域,回调函数 succesCallback 能访问 map 的。


var app = {
    getGeoLoc : function (id) {
        var self = this;
        navigator.geolocation.getCurrentPosition(function(position) {
            var myVar1, myVar2, myVar3;
            self.foundLoc(position, self, myVar1, myVar2, myVar3)
        }, this.noloc, { timeout : 3});
    },
    foundLoc : function(position, self, myVar1, myVar2, myVar3) {},
};

sucessCallback.bind(null, /* 你想传的值 */map);


亲,你这样写的代码就可以完成你的要求(不谈这样写好不好的问题)

【热门文章】
【热门文章】