Javascript 禁止循环函数
函数onSuccess无限期运行,因为它不断地从GPS接收器询问坐标。它包含一个函数createMap,只执行一次。这是如何实现的?使函数之外的函数也不能,因为它是作为参数值传递的函数变量Javascript 禁止循环函数,javascript,Javascript,函数onSuccess无限期运行,因为它不断地从GPS接收器询问坐标。它包含一个函数createMap,只执行一次。这是如何实现的?使函数之外的函数也不能,因为它是作为参数值传递的函数变量 watchID = navigator.geolocation.watchPosition(function(position) {onSuccess(position, arrMyLatLng);}, onError, options); function onSuccess(position, ar
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) ;
}
只运行一次的函数:
function runOnce() {
if (runOnce.done) {
return;
} else {
// do my code ...
runOnce.done = true;
}
}
因为函数是JavaScript中的对象,所以可以在其上设置属性。假设
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”(即为null
)时才会运行,因此createMap只运行一次。您可以使用闭包创建具有私有状态的函数:
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) ;
};
}());
什么是
createMap
?在成功时持续更新,并且“created”始终为false不,在成功第一次运行时,created
将为false,因此if控件结构将运行,创建映射并将created
设置为true。从那时起,下次调用onSuccess,created
都将为真。@user2244523-不,这不是它的工作方式<首次分配onSuccess
时,code>created将设置为false
。请注意,onSuccess
是外部函数返回的(匿名)函数。第一次运行onSuccess
时,created
将设置为true
,无法再次设置为false
。确定。它是如何在watchID=navigator.geolocation.watchPosition(函数(位置){onSuccess(位置,arrMyLatLng);},onError,options)行中修复的@user2244523-为什么该行需要修复?一切都应该按照你的意愿进行。首次调用success callback函数时,它会将privatecreated
变量设置为true
,从那时起,回调将跳过对createMap
的调用。试试看!