I'm trying to define functions in a loop in javascript...
for (var i in myArray) {
Object.defineProperty(object, "field"+i, { ... });
}
...and each function needs to make use of a variable which is set in that loop...
for (var i in myArray) {
Object.defineProperty(object, "field"+i, {
get: function() { return "some operation" + myArray[i]; }
});
}
...but this doesn't work because when I call the functions (long after they're defined), i
evaluates to the last item in the myArray
. All of the functions I defined in the loop return the same (erroneous) value.
Can anyone tell me how to accomplish my aim: make use of myArray[i]
within my getter function?