I have a Google Map, and I am adding event listeners to different things. For instance, I have a Point object, and for this object, I have been adding events as thus:
google.maps.event.addListener(this.marker, 'click', (function(point) {
return function(event) {
alert(point.index);
}})(this));
I have a lot of these events (one for ‘click’, ‘rightclick’, ‘doubleclick’, etc).
When I am adding the event, I create a closure specifically around only the current point. What I am tempted to do however is just:
var point = this;
google.maps.event.addListener(this.marker, 'click', function(event) {
alert(point.index);
});
I have been avoiding this though because of two reasons.
One is that I’ve seen people that know more about Javascript than I do using “individual” closures, so I figure they must have a good reason.
The second is because (and I don’t know anything about how Javascript is interpreted) I wonder if creating a large closure captures all of the other variables I’m not going to use in my event function (e.g. ‘var color’). Could this cause performance problems?
Thanks for the help!
Both your examples create closures over something called
point. In the first one,pointis a parameter to the outer anonymous function, and in the second one,pointis a local variable. But either way, it is ultimately closed over by an anonymous function.Creating an anonymous function accepting one named parameter and then immediately calling it with an argument is just one way of binding a value to a name within a scope.
Or:
The difference is that by using a function, you ensure that the
xlives in its own namespace and will not be merged with any otherxin the enclosing scope. That is, the value is in maintainability, not speed of execution.Which will perform better? The only way to find out is to test on multiple browsers – they all have their own execution engines.
It seems reasonable to think that the more anonymous functions are created, the more small allocations occur. So your second example, with fewer anonymous functions, may perform better. But that is pure unfounded guesswork without testing in every browser you care about.