The fact that functions are objects in JavaScript is a great thing but combined with anonyms functions you can solve scoping problems, though in the process create more.

Take the following code:

function msg(m)
{
window.addEventListener("click", function ()
{
alert(m);
});
}

It works exactly as you’d expect, an alert with the given message every time the user clicks on the page. Call it 10 times with different value and you’ll get 10 alerts each with the correct message.

What if we did the following though:

function ()
{
for(var i 0l i < 10; i++)
{
window.addEventListener("click", function ()
{
alert(i);
});
}
}

A C# developer would think you’d see 10 alerts counting from 0 to 9. In fact what you’ll see is 10 alerts saying 9. The reason for this is that JavaScript looks at the value of ‘i’ at the time the anonyms function executes. The last value it’s given is 9 so all 10 functions see that value.

A C# developer doesn’t expect that because the .NET framework doesn’t do that but instead saves the value at the time of creation. It’s a very useful ability that I have used many times, till today.

In porting my XNA code to MonoGame I learnt that the Mono Framework apparently handles this situation like JavaScript. Just Like JavaScript there are easy ways to fix this, just save the value of ‘i’ so that the function uses the saved value instead. In JavaScript you need to create a wrapping function to create a new scope. C# is a bit easier since it has block level scoping you can just create a new variable to store the value.

  1. shmuelie posted this
Blog comments powered by Disqus