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

How can I avoid creating a function within this loop?

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);
}

我正在处理我的个人项目和下面的代码,我收到错误消息 W083 不要在循环中创建函数 关于如何修复此错误的任何想法?文件: 消息:'Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. (W083)' 在:'99,53' 来源:'jshint' 代码:'W083'

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

function createMarkers(locations, infowindow) {

    // Create the listener function
    var markerClickListener = function(marker, infowindow) {
        return function() {
            getVenueDetails(marker.position, marker.city, marker.title, function(windowContent) {
                infowindow.setContent(windowContent);
                infowindow.open(map, marker);
            });
        };
    };


    // 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);

        //Pass The function declared above
        google.maps.event.addListener(marker, 'click', markerClickListener(marker, infowindow));

        bounds.extend(position);

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