0

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?

JellicleCat
  • 28,480
  • 24
  • 109
  • 162
  • 2
    Take a look at this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake. –  Apr 22 '14 at 17:42
  • possible duplicate of [Jquery Loop not working correctly?](http://stackoverflow.com/questions/19318554/jquery-loop-not-working-correctly) – Denys Séguret Apr 22 '14 at 17:42
  • @procrastinator, awesome. Thank you. I used a factory function to solve the problem. – JellicleCat Apr 22 '14 at 17:48
  • Off-topic: `for..in` loops are a bad way of iterating arrays. You should use ES6 `for..of` (currently only supported by FF), or a `for(var i=0, l=myArray.length; i – Oriol Apr 22 '14 at 18:46
  • Not an awesome-sounding idea. Avoid array indices, which are more powerful than array elements? Support only a single browser? How about you give some indication of why `for..in` loops are a 'bad' way of iterating arrays? – JellicleCat Apr 23 '14 at 01:38

2 Answers2

1

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])
  });
}
JellicleCat
  • 28,480
  • 24
  • 109
  • 162
0

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