如何避免在此循环中创建函数?

时间:2018-03-10 04:58:56

标签: javascript jshint



function createMarkers(locations, infowindow) {
  // create an array of markers from Model data
  for (var i = 0; i < locations.length; i++) {
    // Get the position from the location array.
    var position = locations[i].location;
    var title = locations[i].title;
    // Create a marker per location
    var marker = new google.maps.Marker({
      map: map,
      position: position,
      title: title,
      address: locations[i].address,
      city: locations[i].city,
      url: locations[i].url,
      animation: google.maps.Animation.DROP
    });

    // Push the marker.
    markers.push(marker);

    google.maps.event.addListener(marker, 'click', (function (marker, infowindow) {
      return function () {
        getVenueDetails(marker.position, marker.city, marker.title, function (windowContent) {
          infowindow.setContent(windowContent);
          infowindow.open(map, marker);
        });
      };
    })(marker, infowindow));

    bounds.extend(position);

  }
  // Extend the boundaries of the map for each marker
  map.fitBounds(bounds);
}
&#13;
&#13;
&#13;

我正在处理我的个人项目,并在下面的代码中收到错误消息W083不要在循环中创建有关如何修复此错误的任何想法?文件: message:&#39;在循环中声明的引用外部范围变量的函数可能会导致语义混乱。 (W083)&#39; at:&#39; 99,53&#39; 来源:&#39; jshint&#39; 代码:&#39; W083&#39;

1 个答案:

答案 0 :(得分:1)

而不是在循环中创建函数,即使用function关键字是一个循环,创建一个变量作为函数的引用,在我的示例中为markerClickListener,并将其传递给{{ 1}}。

addListener