2010-05-31 71 views
2

我这里有一些代码:http://bitbucket.org/natim/lo53_tp1/src/tip/part3/camions/medias/js/tracking.js内联函数和全局变量的问题在Javascript

我用来得出卡车上的一些信息。

的问题在规定的for循环像这样的一个函数来:

... 

for(i = 0; i < nb_trucks; i++) 
{ 
    ... 

    contentString = '<div id="content">'+ trucks[i]['name'] + '</div>'; 

    current_window = new google.maps.InfoWindow({ 
     content: contentString 
    });    

    infosWindow.push(current_window); 

    current_marker = new google.maps.Marker({ 
     map: map, 
     position: new google.maps.LatLng(trucks[i]['end']['lat'], trucks[i]['end']['lon']), 
     draggable: false, 
     title: trucks[i]['name'] 
    }); 
    markers.push(current_marker); 

    google.maps.event.addListener(current_marker, 'click', function() { 
     current_window.open(map, current_marker); 
    }); 
} 

在这段代码中,你可以看到的最后一块

google.maps.event.addListener(current_marker, 'click', function() { 
     current_window.open(map, current_marker); 
    }); 

而且我的问题是在current_marker addListener参数与函数内部的参数不同。

函数内的current_window和current_marker在每个循环中都被覆盖。

我该如何解决问题?

感谢

+0

你真的应该习惯用'var' – Pointy 2010-05-31 13:31:41

+0

来声明变量哪一个不是?我在完整文件的for循环之外做了它。 – Natim 2010-05-31 13:42:38

回答

4

closure把它包(只是这个小部分,没有其他变化),所以你得到你想要的变量,就像这样:

(function(marker) { //a copy is passed, accessible as marker inside this function 
    google.maps.event.addListener(marker, 'click', function() { 
    current_window.open(map, marker); 
    }); 
})(current_marker); //pass in the current value 

这不引用相同的变量每一个循环都会改变它的一个副本,所以每次运行时都会得到一个current_marker那个时间点通过的副本。如果你对此更加好奇,there are some great answers explaining closures in this question

+0

非常感谢,这正是我想要的! – Natim 2010-05-31 13:16:43

+0

也许使用类似Prototype的.bind()方法也行。 – Dormilich 2010-05-31 13:17:09

+0

@Dormilich:这也仅仅是一个闭包,虽然包裹在其他代码中......但在这种情况下,核心JavaScript很容易做到这一点,没有理由为这样的任何东西包含一个库。 – 2010-05-31 13:20:19