I have a loop that adds a function to an object for each iteration. These functions are called later to change the innerHTML of several elements. The problem I am running into is that the values returned by the function calls are not what I expect. The results that I expect are shown as comments next to each function call below. Any help would be appreciated.
var set = [1, 2, 3];
var obj = {};
for (var i = 0; i < set.length; i++) {
obj['obj' + i] = {
func: function() {
return ['test', i].join('');
}
}
}
document.getElementById("obj0").innerHTML = obj.obj0.func(); // test1
document.getElementById("obj1").innerHTML = obj.obj1.func(); // test2
document.getElementById("obj2").innerHTML = obj.obj2.func(); // test3
<div id='obj0'></div>
<div id='obj1'></div>
<div id='obj2'></div>