Variables in Javascript Nested Functions

Like many programming/scripting languages, Javscript provides the ability to nest one function inside another function, a bit like this:

function outside () {

function inside() {

window.alert(‘Hello World’);

}

}

This behaviour is most commonly seen when a developer needs to assign a function to an event that is created inside another function, for instance:

function outside () {

var menu =document.createElement(‘SELECT’);

menu.onchange = function () {

window.alert(‘Hello World’);

}

}

One of the difficulties that can arise here is that quite often it is necessary to pass a variable to the inner function. Say for instance, you want to create a 3 SELECTs, each having an onChange event which displays an alert unique to that SELECT. Would this work?

function outside () {

for (i=1;i<4;i++) {

var menu =document.createElement(‘SELECT’);

menu.id = i;

menu.onchange = function (i) {

window.alert(‘Menu’ + document.getElementById(i).id);

}

}

}

The simple answer is that no, it won’t.

What this execution will do is run the inner function at the same time as the outer function and assign the return value of the inner function to the ‘onchange’ property of the SELECT object, even if nothing is returned.

This isn’t what we want. What we want is for the inner function to be assigned to the onChange event of the SELECT.

There are couple of ways to do this, 3 of which are very well explained in this article.

Here’s one of them. What we do in this case is create a new property for the SELECT object, to which we assign the necessary variables, which we can then reference with the this object reference.

function outside () {

for (i=1;i<4;i++) {

var menu =document.createElement(‘SELECT’);

menu.menuid = i;

menu.onchange = function () {

window.alert(‘Menu’ + this.menuid);

}

}

}

This method isn’t without its problems either, but it will work in the majority of cases. If you want the Gold Standard solution, check out the referenced article above, preferably from a quiet, well-aired room with a nice view of distant snow-capped mountains (ie its a little complicated…)