Reputation: 30236
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?
Upvotes: 0
Views: 57
Reputation: 30236
I created an extra closure by using a factory function:
function makeGetter(myString) {
return function () { return "some operation" + myString; };
}
for (var i in myArray) {
Object.defineProperty(object, "field"+i, {
get: makeGetter(myArray[i])
});
}
Upvotes: 1
Reputation:
this could be done as following
for (var i in myArray)
{
var getter=function yourName () { return "some operation" + yourName.data;}
getter.data=myArray[i];
Object.defineProperty(object, "field"+i, {
get: getter});
}
you can define a function with
var test=function testit () {}
testit can be use to call the function from inside the function. its a locale variable inside, its replacing arguments.callee which is depreacted in strict mode.
test is defined outside the function to call it from outside
Upvotes: 0