0

函数 onSuccess 无限期地运行,因为不断地询问 GPS 接收器的坐标。它包含一个函数 createMap,只执行一次。这是如何实现的?使函数外的函数也不能,因为它是作为函数变量的参数值传递的。

watchID = navigator.geolocation.watchPosition(function(position) {onSuccess(position, arrMyLatLng);}, onError, options);  

function onSuccess(position, arrMyLatLng) 
{

var latitude , longitude ;     
latitude = position.coords.latitude ;
longitude = position.coords.longitude;
var myLatLng = new google.maps.LatLng(latitude, longitude);

createMap(myLatLng, arrMyLatLng);// This feature will run for an indefinite number of times. It is only necessary once. 
map.panTo(myLatLng) ;
}
4

3 回答 3

1

只运行一次的函数:

function runOnce() {
    if (runOnce.done) {
         return;
    } else {
       // do my code ...

       runOnce.done = true;
    }
}

因为函数在 JavaScript 中是对象,所以你可以在它上面设置一个属性。

于 2013-04-09T20:06:15.093 回答
1

您可以使用闭包创建具有私有状态的函数:

onSuccess = (function() {
    var created = false;
    return function (position, arrMyLatLng) {
        var latitude , longitude ;     
        latitude = position.coords.latitude ;
        longitude = position.coords.longitude;
        var myLatLng = new google.maps.LatLng(latitude, longitude);
        if (!created) {
            createMap(myLatLng, arrMyLatLng);
            created = true;
        }
        map.panTo(myLatLng) ;
    };
}());
于 2013-04-09T20:06:39.423 回答
0

假设createMap返回一个地图

var map = null;

function onSuccess(position, arrMyLatLng) {
    var latitude = position.coords.latitude ;
    var longitude = position.coords.longitude;
    var myLatLng = new google.maps.LatLng(latitude, longitude);

    map = map || createMap(myLatLng, arrMyLatLng);
    map.panTo(myLatLng);
}

createMap只有在map评估为“false”(即 is null)时才会运行,因此 createMap 只运行一次。

于 2013-04-09T20:06:24.493 回答