I will begin by explaining what I am trying to do here with a simple example.
- Create a local scope variable id and give it a value x.
- Create a function expression where I print out the value x by means of alert(a); and store that function as a variable fn in a global list.
- Modify id to represent the value y.
- Call fn(); through my global list and have x printed out for me.
The problem now is that the value printed by fn() is y and not x as was initially assigned to id. I first found a solution by dealing with temporary global variables, but it simply doesn't work anymore as the project has grown quite a bit. I no longer have the means required to keep track of these global temps.
Any help to point me in the right direction would be appreciated. I apology if this question has been answered before. Perhaps I am just not very good at searching the web, but I have yet to find a satisfying one.
Note: I should perhaps add that contrary to the amount of times I mentioned the variable scopes, it is not a problem. The local variable seems to somehow be treated globally (or perhaps a global pointer to it is created?) as there is no problem printing a local variable from other scopes when done in the manner described above.
Here is a code sample of what I want (I decided it would be clearer this way than using my own code):
var fnList = []
function FunctionA(){
for(var i = 0; i < 10; i++){
var iToFunctionExpression = i; // this is where I want to somehow send my variable to the function
fnList.push(function(){
alert(iToFunctionExpression);
});
}
}
function FunctionB(){
for(var i = 10; i < 20; i++){
var iToFunctionExpression = i; // this is where I want to somehow send my variable to the function
fnList.push(function(){
alert(iToFunctionExpression);
});
}
}
function FunctionPrintAB(){
for(var fn = 0; fn < fnList.length; fn++){
fnList[fn](); // here I want to alert the numbers 0 through 19
}
}
Best regards.