不要在循环jshint中创建函数

时间:2017-05-15 06:19:03

标签: javascript

for (var p = 0; p < tokiyoPoints.length; p++) { //for loop
        var tpoint = new google.maps.Marker({ //MAP MARKER
            map: map, //MAP BY ID
            //MARKER DROP
            animation: google.maps.Animation.DROP,
            venue: tokiyoPoints[p].pointId, //FOR LIKES AND RATING
            title: tokiyoPoints[p].pointName, //TITLE OF POINT
            show: ko.observable(true), //SHOW POINT
            selected: ko.observable(false), //SELECT POINT
            position: { //POINT POSITION
                lat: tokiyoPoints[p].pointLat,
                lng: tokiyoPoints[p].pointLng
            }
        });
        tokiyo.push(tpoint); //ADD POINT AT THE END
        tpoint.addListener('click', function() {
            //CLICK ON THE POINTER
            pointerInfo(this, tokyoInfo);
        });
        tpoint.addListener('click', function() {
            //CLICK ON THE POINTER
            BOUNCE(this);
        });

    tpoint.addListener('mouseover', function() {
            //MOSEOVER ON POINT
            this.setIcon(nIcon);
        });
        tpoint.addListener('mouseout', function() {
            //MOUSEOUT FROM THE POINTER
            this.setIcon(uIcon);
        });
    }

它给出了错误 -

  

不要在循环js中创建函数

1 个答案:

答案 0 :(得分:0)

抛出错误的原因是因为您在循环中创建函数(事件处理程序)。

因此,如果您说100分,您将创建400个函数,但它们的结构将保持不变。避免这种情况的正确方法是在循环外部使用命名函数,并将这些函数的引用传递给事件。

for (var p = 0; p < tokiyoPoints.length; p++) { //for loop
  var tpoint = new google.maps.Marker({ //MAP MARKER
    map: map, //MAP BY ID
    //MARKER DROP
    animation: google.maps.Animation.DROP,
    venue: tokiyoPoints[p].pointId, //FOR LIKES AND RATING
    title: tokiyoPoints[p].pointName, //TITLE OF POINT
    show: ko.observable(true), //SHOW POINT
    selected: ko.observable(false), //SELECT POINT
    position: { //POINT POSITION
      lat: tokiyoPoints[p].pointLat,
      lng: tokiyoPoints[p].pointLng
    }
  });
  tokiyo.push(tpoint); //ADD POINT AT THE END
  tpoint.addListener('click', clickHandler1);
  tpoint.addListener('click', clickHandler2);

  tpoint.addListener('mouseover', mouseOverHandler);
  tpoint.addListener('mouseout', mouseOutHandler);
}

function clickHandler1() {
  //CLICK ON THE POINTER
  pointerInfo(this, tokyoInfo);
}

function clickHandler2() {
  //CLICK ON THE POINTER
  BOUNCE(this);
}

function mouseOverHandler() {
  //MOSEOVER ON POINT
  this.setIcon(nIcon);
}

function mouseOutHandler() {
  //MOUSEOUT FROM THE POINTER
  this.setIcon(uIcon);
}