Javascript 中的内联函数和全局变量问题

Nat*_*tim 2 javascript global-variables

我这里有一些代码:http : //bitbucket.org/natim/lo53_tp1/src/tip/part3/camions/medias/js/tracking.js

我用来绘制一些关于卡车方向的信息。

问题来自在 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);
    });
}
Run Code Online (Sandbox Code Playgroud)

在这段代码中,您可以看到最后一个块

    google.maps.event.addListener(current_marker, 'click', function() {
        current_window.open(map, current_marker);
    });
Run Code Online (Sandbox Code Playgroud)

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

函数内的 current_window 和 current_marker 在每次循环时都会被覆盖。

我怎样才能做对?

谢谢

Nic*_*ver 5

将它包裹在一个闭包中(只是这个小部分,没有其他变化),这样你就可以得到你想要的变量,像这样:

(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
Run Code Online (Sandbox Code Playgroud)

这不引用正在改变每个循环相同的变量,它的一个拷贝被传递到关闭,所以每次运行这个它得到一个什么样的副本current_marker那那个时候在过去了。如果你更好奇这,有一些很好的答案解释了这个问题中的闭包