Google Maps API 3 - JavaScript 中的闭包

google maps api 3 - closure in javascript

本文关键字:闭包 JavaScript Maps API Google      更新时间:2023-09-26
function initialize(final) 
{
    if (GBrowserIsCompatible()) {
             ................................................
        }
        var address_array = final.split('~');
        for (var count = 0; count < address_array.length; count++) {
            if (geocoder) {
                geocoder.getLatLng(
        address_array[count],
        makeTheFunction(address_array, count)
    );
            }
        }
  }

  function makeTheFunction(array, thisCount) {
      return function (point) {
          if (!point) {
              alert(array[thisCount] + " not found");
          }

          else {
              var marker = new GMarker(point);
              map.addOverlay(marker);
              GEvent.addListener(marker, "click", function () {
                  marker.openInfoWindowHtml(array[thisCount] + "</b>");
              });
          }
      };
  }

我的问题是我无法从 else 部分访问array[thisCount],尽管它可以从 if 块访问.. 即alert(array[thisCount] + " not found");正在工作请帮忙

else 块或"click"处理程序中无法访问它吗?如果您不能仅在"单击"处理程序中获取 array/thisCount,您是否尝试过复制这些变量?这可能是上下文的问题吗?试试这个,如果你的数组在 else 块中可见:

function makeTheFunction(array, thisCount) {
  return function (point) {
      if (!point) {
          alert(array[thisCount] + " not found");
      }

      else {
          var item = array[thisCount];
          var marker = new GMarker(point);
          map.addOverlay(marker);
          GEvent.addListener(marker, "click", function () {
              marker.openInfoWindowHtml(item + "</b>");
          });
      }
  };

}

function makeTheFunction(array, thisCount) 
{         
          if (!point) 
          {
              alert(array[thisCount] + " not found");
          }
          else 
          {
              var marker = new GMarker(point);
              map.addOverlay(marker);
              GEvent.addListener(marker, "click", function () {
                  marker.openInfoWindowHtml(array[thisCount] + "</b>");
              });
          }
      return point;
  }

我建议addListener函数中出现问题。在提供的代码中,侦听器中的thisCount应该在makeTheFunction函数中对 thisCount 有一个闭包。

下面模拟发布的代码:

<script type="text/javascript">
function init() {
  var count = 'the count';
  partTwo(makeFn(count));
  function makeFn(thisCount) {
    return function() {
      // Shows 'thisCount: the count'
      alert('thisCount: ' + thisCount);
      document.getElementById('btn0').addEventListener('click',
        function(){alert('thisCount: ' + thisCount);}, false);
    }
  }
}
function partTwo(fn) {
  fn();
}
window.onload = function() {
  init();
};
</script>
<!-- Shows 'thisCount: the count' -->   
<button id="btn0">Button 0</button>

但是,它使用浏览器addEventListener附加侦听器,而不是明显的自定义addListener