Hello, please sign in or register
You are here: Home

Javascript lambda functions and closures

Lambda functions and closures are a useful to create functions which inherit properties of their parents at a particular instance... eek!

Example - Misleading

To emphasize here's a common misunderstanding with javascript. If we want to create multiple links, which alert their number the following will all output "5"

<script type='text/javascipt'>
function addLinksWRONG()
{
	for (i=0; i<5; i++)
	{
		link = document.createElement("a");
		link.innerHTML = "Link " + i;
		link.onclick = function(){alert(i);};
		document.body.appendChild(link);
	}
};
window.onload = addLinksWRONG;
</script>

TEST: Example 1:

 

Example - Correct

But if we nest another function binding those variables, we are "closing" the expression

<script type='text/javascipt'>
function addLinks()
{
	var onclick = function(num){ return function(){alert(num)}};

	for (i=0; i<5; i++)
	{
		link = document.createElement("a");
		link.innerHTML = "Link " + i;
		link.onclick = onclick(i);
		document.body.appendChild(link);
	}
};
window.onload = addLinks;
</script>

TEST: Example 2:

Alternative

Another way of writing this is to set the parameters in the following way

...
link.onclick = (function(num){ return function(){alert(num)}})(i); 
...

Which looks great but the parser is creating a lambda function for each iteration so its not optimal.

This style of coding is quite new to me. But Michel Geary offered this explanation in a comment he left on a great article about javascript interfaces.

 

1: foo = function(){}; foo(); // calls foo
2: foo = function(){}; (foo)(); // calls foo
3: ( function(){} )(); // calls the anonymous function

 

 

References:

Secrets of JavaScript closures, by Stuart Langridge

Explaining JavaScript scope and closures, by Robert Nymann

 

In other languages

PHP 5.3 alpha supports this kind of coding too http://www.php.net/archive/2008.php#id2008-08-01-1 full proposal http://wiki.php.net/rfc/closures... and should be arriving soon.

Comments

Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share