A bunch of little shutters versus one big

I have a Google map and I am adding event listeners to various things. For example, I have a Point object, and for this object I add events this way:

google.maps.event.addListener(this.marker, 'click', (function(point) {
    return function(event) {
        alert(point.index);
    }})(this));

I have many such events (one for 'click', "rightclick", "doubleclick", etc.).

When I add an event, I create a closure only around the current point. However, I am tempted:

var point = this;

google.maps.event.addListener(this.marker, 'click', function(event) {
    alert(point.index);
});

I avoided this, though for two reasons.

Firstly, I saw people who know more about Javascript than I use "separate" closures, so I think they should have a good reason.

-, ( , Javascript). , , (, "var color" "). ?

!

+3
2

-, point. point , , point . .

, , - .

(function(x) { 
    // now x has the value
})(getValue());

:

var x = getValue();
// now x has the value

, , x - x . , , .

? - - .

, , . , . , .

+1

, . , :

var point = this;

google.maps.event.addListener(this.marker, 'click', function(event) {
  alert(point.index);
});

, , , , , :

for(var i = 0, len = points.length; i < len; i++) {
  google.maps.event.addListener(points[i].marker, 'click', (function(point) {
    return function(event) {
      alert(point.index);
    }
  })(points[i]));
}

, .

+1

Source: https://habr.com/ru/post/1759810/


All Articles