[Last Call] Learn how to a build a cloud-first strategyRegister Now


Javascript - references / pointers to objects problem

Posted on 2009-03-29
Medium Priority
Last Modified: 2012-05-06

I add Google Maps Markers on a map, and want to bind a click event on each of them: I add the markers on the map in a loop, so the binding of the event is done in the loop for each marker.
But it seems that when I click on the markers on the map, the callback function will execute the same instructions for all the markers: the instructions that have been set for the last marker.
It seems to be a problem with the references ...
Here is code to make it all clear:

for(key in data) {
      var pointDep = new GLatLng(data[key][2], data[key][1]);
      var markerDep = new GMarker(pointDep, icon);
      GEvent.addListener(markerDep, "click", function() {

When loading the page, the first alert will for example display:

And the alert inside the event listener will only display D when I click on any marker. I was expecting respectively to get alerts of A, B, C and D.

They need to acheive the same in this tutorial:
(Using Closures in Event Listeners)
They also add the markers via a loop, so I can't understand why my code doesn't work and their does. Some difference somewhere ...

Thank you for any help!
Question by:debussy007
  • 3
  • 2
LVL 13

Expert Comment

ID: 24014929
Here is an example of how to create a closure. The example is on a simple loop between 3 numbers. Try the example as it is, and then have a go with the non-bound function.

For a more complete events and function binding system I would strongly recommend the Prototype Framework for JavaScript (3rd example in source). http://www.prototypejs.org
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
		<title>Demo Page</title>
		<script type="text/javascript">
			// A simple bind function which creates a closure.
			function bind(fn, context, data) {
				return function() {
					return fn.call(context, data);
			// Array to store bound functions.
			var c = [];
			// Iterate through a sequence of numbers.
			for (var i = 0; i < 3; ++i) {
				c.push(bind(function(data) {
					// Display the bound data, in this example the value of "i".
				}, this, i));
				// Replace the above with the following to see the non-bound version:
				//c.push(function() {
				//	alert(i);
				// The following shows how simple this would be with PrototypeJS:
				// Note: You will need Protoype for this to work!
				//c.push(function(data) {
				//	alert(data);
			// Call each of the bound functions in turn.
		<h1>Demo Page</h1>

Open in new window


Author Comment

ID: 24027661
I would like to udnerstand the problem of my code, to get a little smarter.
Also, I don't know what a closure is.

LVL 13

Accepted Solution

numberkruncher earned 460 total points
ID: 24027874
You can create a closure when you place a function inside a function.

I will try to walk you through an example. Take a look at SOURCE #1 below. This is a straight-forward function "foo" which sets up a variable called "myVariable", does something with it, and then finishes. This variable is stored within the calling context of "foo", and is only available during that time. Once "foo" has finished, the variable is no longer available.

SOURCE #2 constructs a closure because its "myVariable" remains accessible even after "foo" has finished running. The function that is generated by "foo" remembers the state that "foo" was in at that exact time. So, when this generated function is called, it has access to the original "myVariable" instance.

SOURCE #2 then moves on to execute the generated function, and the value "12" appears in an alert box. The generated function is able to do this because it has access to the original variable.

So.......WHY? Why would we do this?

By creating a closure we were able to maintain each key, as opposed to just the last one.

Here is a website which might help explain it more clearly:

// SOURCE #1
function foo()
   // Set up a variable in the context of "foo".
   var myVariable = 12;
   // Variable can then be used.
// "myVariable" is not available outside of function "foo".
// SOURCE #2
function foo()
   // Set up a variable in the context of "foo".
   var myVariable = 12;
   // Define and return a new function.
   return function() {
       // "myVariable" is still available event after "foo" has finished.
// Use foo to get the generated function.
var bar = foo();
// Now if we call "bar", the variable gets displayed on screen.

Open in new window


Author Comment

ID: 24028316
I think I get you ...

And what would be the "normal" way to do this without the closures ?
E.g. never heard about closures in other languages.
LVL 13

Expert Comment

ID: 24028538
Other languages deal with events in a different way. Usually the code which fires an event handler has access to the event arguments, and can provide them there and then.

When you bind a DOM event in JavaScript you need a mechanism to associate information with each event handler. One of the simplest ways of doing this in JavaScript is to construct a closure. Closures are an extremely powerful asset of JavaScript, especially if you want to emulate things like classes and namespaces.

As far as I am aware, closures are the only realistic way to achieve this in JavaScript. The only other way that I know of would be to create a lookup table, but this could damage performance, and would be a lot more difficult to manage.

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question