代码之家  ›  专栏  ›  技术社区  ›  Natim

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

  •  2
  • Natim  · 技术社区  · 14 年前

    我这里有一些代码: 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);
        });
    }
    

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

    我的问题是addListener参数中当前的\u标记与函数中的不同。

    函数中的当前\u窗口和当前\u标记在每个循环圈的上方。

    谢谢

    1 回复  |  直到 14 年前
        1
  •  5
  •   Community CDub    7 年前

    把它包起来 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 .